custom_error.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package xerr
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "kpt-tmr-group/pkg/logger/logrus"
  7. )
  8. // Custom biz custom error
  9. func Custom(msg string) error {
  10. return wrapStack(&CustomError{msg: msg}, 1)
  11. }
  12. // Customf biz custom error, formats according to a format specifier
  13. func Customf(format string, a ...interface{}) error {
  14. return wrapStack(&CustomError{msg: fmt.Sprintf(format, a...)}, 1)
  15. }
  16. // CustomError 业务错误代码,不应该返回 500 错误
  17. // 同时,这个错误不会上传到 NewRelic
  18. type CustomError struct {
  19. msg string
  20. }
  21. func (e *CustomError) Error() string {
  22. return e.msg
  23. }
  24. func (e *CustomError) CustomError() bool {
  25. return true
  26. }
  27. // IsCustomError 判断是否为业务错误
  28. func IsCustomError(err error) (error, bool) {
  29. type custom interface {
  30. CustomError() bool
  31. }
  32. _, ok := Cause(err).(custom)
  33. return err, ok
  34. }
  35. // IgnoreDuplicateEntryError ignore duplicate entry error,
  36. // return nil if error message contain Duplicate entry,
  37. // return err in other errors.
  38. func IgnoreDuplicateEntryError(err error, msg ...interface{}) error {
  39. if IsUniqueError(err) {
  40. if len(msg) != 0 {
  41. bs, _ := json.Marshal(msg)
  42. logrus.Debugf("ignore duplicate record %s", string(bs))
  43. }
  44. return nil
  45. }
  46. return wrapStack(err, 1)
  47. }
  48. // IsUniqueError 判断是否是 sql unique 错误
  49. func IsUniqueError(err error) bool {
  50. if err == nil {
  51. return false
  52. }
  53. return strings.Contains(err.Error(), "Duplicate entry")
  54. }