errcode.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package errors
  2. import "net/http"
  3. import "github.com/novalagung/gubrak"
  4. var (
  5. unknownCoder ErrCode = ErrCode{1, http.StatusInternalServerError, "An internal server error occurred", ""}
  6. )
  7. type ErrCode struct {
  8. // 业务错误码
  9. C int
  10. // http码
  11. HTTP int
  12. // 对外展示错误信息
  13. Ext string
  14. // 引用
  15. Ref string
  16. }
  17. func (coder ErrCode) Code() int {
  18. return coder.C
  19. }
  20. func (coder ErrCode) String() string {
  21. return coder.Ext
  22. }
  23. func (coder ErrCode) Reference() string {
  24. return coder.Ref
  25. }
  26. func (coder ErrCode) HTTPStatus() int {
  27. if coder.HTTP == 0 {
  28. return http.StatusInternalServerError
  29. }
  30. return coder.HTTP
  31. }
  32. func RegisterCode(code int, httpStatus int, message string, refs ...string) {
  33. found, _ := gubrak.Includes([]int{200, 400, 401, 403, 404, 500}, httpStatus)
  34. if !found {
  35. panic("http code not in `200, 400, 401, 403, 404, 500`")
  36. }
  37. var reference string
  38. if len(refs) > 0 {
  39. reference = refs[0]
  40. }
  41. coder := &ErrCode{
  42. C: code,
  43. HTTP: httpStatus,
  44. Ext: message,
  45. Ref: reference,
  46. }
  47. MustRegister(coder)
  48. }