errors.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package gorm
  2. import (
  3. "errors"
  4. "strings"
  5. )
  6. var (
  7. // ErrRecordNotFound returns a "record not found error". Occurs only when attempting to query the database with a struct; querying with a slice won't return this error
  8. ErrRecordNotFound = errors.New("record not found")
  9. // ErrInvalidSQL occurs when you attempt a query with invalid SQL
  10. ErrInvalidSQL = errors.New("invalid SQL")
  11. // ErrInvalidTransaction occurs when you are trying to `Commit` or `Rollback`
  12. ErrInvalidTransaction = errors.New("no valid transaction")
  13. // ErrCantStartTransaction can't start transaction when you are trying to start one with `Begin`
  14. ErrCantStartTransaction = errors.New("can't start transaction")
  15. // ErrUnaddressable unaddressable value
  16. ErrUnaddressable = errors.New("using unaddressable value")
  17. )
  18. // Errors contains all happened errors
  19. type Errors []error
  20. // IsRecordNotFoundError returns true if error contains a RecordNotFound error
  21. func IsRecordNotFoundError(err error) bool {
  22. if errs, ok := err.(Errors); ok {
  23. for _, err := range errs {
  24. if err == ErrRecordNotFound {
  25. return true
  26. }
  27. }
  28. }
  29. return err == ErrRecordNotFound
  30. }
  31. // GetErrors gets all errors that have occurred and returns a slice of errors (Error type)
  32. func (errs Errors) GetErrors() []error {
  33. return errs
  34. }
  35. // Add adds an error to a given slice of errors
  36. func (errs Errors) Add(newErrors ...error) Errors {
  37. for _, err := range newErrors {
  38. if err == nil {
  39. continue
  40. }
  41. if errors, ok := err.(Errors); ok {
  42. errs = errs.Add(errors...)
  43. } else {
  44. ok = true
  45. for _, e := range errs {
  46. if err == e {
  47. ok = false
  48. }
  49. }
  50. if ok {
  51. errs = append(errs, err)
  52. }
  53. }
  54. }
  55. return errs
  56. }
  57. // Error takes a slice of all errors that have occurred and returns it as a formatted string
  58. func (errs Errors) Error() string {
  59. var errors = []string{}
  60. for _, e := range errs {
  61. errors = append(errors, e.Error())
  62. }
  63. return strings.Join(errors, "; ")
  64. }