errors.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Package errors provides a way to return detailed information
  2. // for an RPC request error. The error is normally JSON encoded.
  3. package errors
  4. import (
  5. "errors"
  6. "fmt"
  7. json "github.com/json-iterator/go"
  8. )
  9. //go:generate protoc -I. --go_out=paths=source_relative:. errors.proto
  10. const (
  11. Silent = "0"
  12. MessageWarn = "1"
  13. MessageError = "2"
  14. Notification = "4"
  15. Page = "9"
  16. )
  17. func (e *Error) Error() string {
  18. b, _ := json.Marshal(e)
  19. return string(b)
  20. }
  21. // New generates a custom error.
  22. func New(id, domain string, code ErrorCoder) error {
  23. return &Error{
  24. ErrorCode: fmt.Sprintf("C%d", code.Code()),
  25. ErrorMessage: code.String(),
  26. ShowType: MessageError,
  27. TraceId: id,
  28. Domain: domain,
  29. }
  30. }
  31. // Parse tries to parse a JSON string into an error. If that
  32. // fails, it will set the given string as the error detail.
  33. func Parse(errStr string) *Error {
  34. e := new(Error)
  35. err := json.Unmarshal([]byte(errStr), e)
  36. if err != nil {
  37. e.ErrorMessage = errStr
  38. }
  39. return e
  40. }
  41. // Equal tries to compare errors
  42. func Equal(err1 error, err2 error) bool {
  43. var vErr1 *Error
  44. ok1 := errors.As(err1, &vErr1)
  45. var vErr2 *Error
  46. ok2 := errors.As(err2, &vErr2)
  47. if ok1 != ok2 {
  48. return false
  49. }
  50. if !ok1 {
  51. return errors.Is(err1, err2)
  52. }
  53. if vErr1.ErrorCode != vErr2.ErrorCode {
  54. return false
  55. }
  56. return true
  57. }
  58. // FromError try to convert go error to *Error
  59. func FromError(err error) *Error {
  60. var vErr *Error
  61. if errors.As(err, &vErr) && vErr != nil {
  62. return vErr
  63. }
  64. return Parse(err.Error())
  65. }