error.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package common
  2. import (
  3. "errors"
  4. )
  5. // Code is the error code.
  6. type Code int
  7. // Application error codes.
  8. const (
  9. // 0 ~ 99 general error.
  10. Ok Code = 0
  11. Internal Code = 1
  12. NotAuthorized Code = 2
  13. Invalid Code = 3
  14. NotFound Code = 4
  15. Conflict Code = 5
  16. NotImplemented Code = 6
  17. )
  18. // Error represents an application-specific error. Application errors can be
  19. // unwrapped by the caller to extract out the code & message.
  20. //
  21. // Any non-application error (such as a disk error) should be reported as an
  22. // Internal error and the human user should only see "Internal error" as the
  23. // message. These low-level internal error details should only be logged and
  24. // reported to the operator of the application (not the end user).
  25. type Error struct {
  26. // Machine-readable error code.
  27. Code Code
  28. // Embedded error.
  29. Err error
  30. }
  31. // Error implements the error interface. Not used by the application otherwise.
  32. func (e *Error) Error() string {
  33. return e.Err.Error()
  34. }
  35. // ErrorCode unwraps an application error and returns its code.
  36. // Non-application errors always return EINTERNAL.
  37. func ErrorCode(err error) Code {
  38. var e *Error
  39. if err == nil {
  40. return Ok
  41. } else if errors.As(err, &e) {
  42. return e.Code
  43. }
  44. return Internal
  45. }
  46. // ErrorMessage unwraps an application error and returns its message.
  47. // Non-application errors always return "Internal error".
  48. func ErrorMessage(err error) string {
  49. var e *Error
  50. if err == nil {
  51. return ""
  52. } else if errors.As(err, &e) {
  53. return e.Err.Error()
  54. }
  55. return "Internal error."
  56. }
  57. // Errorf is a helper function to return an Error with a given code and error.
  58. func Errorf(code Code, err error) *Error {
  59. return &Error{
  60. Code: code,
  61. Err: err,
  62. }
  63. }