errorutil.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. /*
  10. Package errorutil contains common error objects and functions.
  11. */
  12. package errorutil
  13. import (
  14. "bytes"
  15. )
  16. /*
  17. AssertOk will panic on any non-nil error parameter.
  18. */
  19. func AssertOk(err error) {
  20. if err != nil {
  21. panic(err.Error())
  22. }
  23. }
  24. /*
  25. AssertTrue will panic if the given condition is negative.
  26. */
  27. func AssertTrue(condition bool, errString string) {
  28. if !condition {
  29. panic(errString)
  30. }
  31. }
  32. /*
  33. CompositeError can collect multiple errors in a single error object.
  34. */
  35. type CompositeError struct {
  36. Errors []error
  37. }
  38. /*
  39. NewCompositeError creates a new composite error object.
  40. */
  41. func NewCompositeError() *CompositeError {
  42. return &CompositeError{make([]error, 0)}
  43. }
  44. /*
  45. Add adds an error.
  46. */
  47. func (ce *CompositeError) Add(e error) {
  48. ce.Errors = append(ce.Errors, e)
  49. }
  50. /*
  51. HasErrors returns true if any error have been collected.
  52. */
  53. func (ce *CompositeError) HasErrors() bool {
  54. return len(ce.Errors) > 0
  55. }
  56. /*
  57. Error returns all collected errors as a string.
  58. */
  59. func (ce *CompositeError) Error() string {
  60. var buf bytes.Buffer
  61. for i, e := range ce.Errors {
  62. buf.WriteString(e.Error())
  63. if i < len(ce.Errors)-1 {
  64. buf.WriteString("; ")
  65. }
  66. }
  67. return buf.String()
  68. }