When the business requires more complex error code definitions, we can customize the implementation of business error codes by simply implementing the gcode.Code related interface.

Let’s look at an example.

Custom Error Codes

Define the basic business error code structure and implement the gcode.code interface.

  1. type BizCode struct {
  2. code int
  3. message string
  4. detail BizCodeDetail
  5. }
  6. type BizCodeDetail struct {
  7. Code string
  8. HttpCode int
  9. }
  10. func (c BizCode) BizDetail() BizCodeDetail {
  11. return c.detail
  12. }
  13. func (c BizCode) Code() int {
  14. return c.code
  15. }
  16. func (c BizCode) Message() string {
  17. return c.message
  18. }
  19. func (c BizCode) Detail() interface{} {
  20. return c.detail
  21. }
  22. func New(httpCode int, code string, message string) gcode.Code {
  23. return BizCode{
  24. code: 0,
  25. message: message,
  26. detail: BizCodeDetail{
  27. Code: code,
  28. HttpCode: httpCode,
  29. },
  30. }
  31. }

Define business error codes

  1. var (
  2. CodeNil = New(200, "OK", "")
  3. CodeNotFound = New(404, "Not Found", "Resource does not exist")
  4. CodeInternal = New(500, "Internal Error", "An error occurred internally")
  5. // ...
  6. )

Usage in Middleware

  1. func ResponseHandler(r *ghttp.Request) {
  2. r.Middleware.Next()
  3. // There's custom buffer content, it then exits current handler.
  4. if r.Response.BufferLength() > 0 {
  5. return
  6. }
  7. var (
  8. err = r.GetError()
  9. res = r.GetHandlerResponse()
  10. code = gerror.Code(err)
  11. )
  12. if code == gcode.CodeNil && err != nil {
  13. code = CodeInternal
  14. } else {
  15. code = CodeNil
  16. }
  17. if bizCode, ok := code.(BizCode); ok {
  18. r.Response.WriteStatus(bizCode.BizDetail().HttpCode)
  19. }
  20. r.Response.WriteJson(g.Map{
  21. `code`: gcode.CodeOK.Code(),
  22. `message`: gcode.CodeOK.Message(),
  23. `data`: res,
  24. })
  25. }