errorutil.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 "strings"
  14. /*
  15. AssertOk will panic on any non-nil error parameter.
  16. */
  17. func AssertOk(err error) {
  18. if err != nil {
  19. panic(err.Error())
  20. }
  21. }
  22. /*
  23. AssertTrue will panic if the given condition is negative.
  24. */
  25. func AssertTrue(condition bool, errString string) {
  26. if !condition {
  27. panic(errString)
  28. }
  29. }
  30. /*
  31. CompositeError can collect multiple errors in a single error object.
  32. */
  33. type CompositeError struct {
  34. Errors []string
  35. }
  36. /*
  37. NewCompositeError creates a new composite error object.
  38. */
  39. func NewCompositeError() *CompositeError {
  40. return &CompositeError{make([]string, 0)}
  41. }
  42. /*
  43. Add adds an error.
  44. */
  45. func (ce *CompositeError) Add(e error) {
  46. ce.Errors = append(ce.Errors, e.Error())
  47. }
  48. /*
  49. HasErrors returns true if any error have been collected.
  50. */
  51. func (ce *CompositeError) HasErrors() bool {
  52. return len(ce.Errors) > 0
  53. }
  54. /*
  55. Error returns all collected errors as a string.
  56. */
  57. func (ce *CompositeError) Error() string {
  58. return strings.Join(ce.Errors, "; ")
  59. }