Error processing

Overview

Error processing here does not refer to stack handling, error management, etc. but rather to HTTP error handling.

Examples

Let’s simulate an error in the format code-msg when the error is *errors.CodeMsg.

  1. package main
  2. import (
  3. "go/types"
  4. "net/http"
  5. "github.com/zeromicro/go-zero/rest"
  6. "github.com/zeromicro/go-zero/rest/httpx"
  7. "github.com/zeromicro/x/errors"
  8. xhttp "github.com/zeromicro/x/http"
  9. )
  10. func main() {
  11. srv := rest.MustNewServer(rest.RestConf{
  12. Port: 8080,
  13. })
  14. srv.AddRoute(rest.Route{
  15. Method: http.MethodPost,
  16. Path: "/hello",
  17. Handler: handle,
  18. })
  19. defer srv.Stop()
  20. // httpx.SetErrorHandler is only valid if httpx.Error is called to handle the response.
  21. httpx.SetErrorHandler(func(err error) (int, any) {
  22. switch e := err.(type) {
  23. case *errors.CodeMsg:
  24. return http.StatusOK, xhttp.BaseResponse[types.Nil]{
  25. Code: e.Code,
  26. Msg: e.Msg,
  27. }
  28. default:
  29. return http.StatusInternalServerError, nil
  30. }
  31. })
  32. srv.Start()
  33. }
  34. type HelloRequest struct {
  35. Name string `json:"name"`
  36. }
  37. type HelloResponse struct {
  38. Msg string `json:"msg"`
  39. }
  40. func handle(w http.ResponseWriter, r *http.Request) {
  41. var req HelloRequest
  42. if err := httpx.Parse(r, &req); err != nil {
  43. httpx.Error(w, err)
  44. return
  45. }
  46. if req.Name == "error" {
  47. // mock parameter error
  48. httpx.Error(w, errors.New(400, "dummy error"))
  49. return
  50. }
  51. httpx.OkJson(w, HelloResponse{
  52. Msg: "hello " + req.Name,
  53. })
  54. }
  1. $ curl --location '127.0.0.1:8080/hello' \
  2. --header 'Content-Type: application/json' \
  3. --data '{
  4. "name":"go-zero"
  5. }'
  6. {"msg":"hello go-zero"}
  7. $ curl --location '127.0.0.1:8080/hello' \
  8. --header 'Content-Type: application/json' \
  9. --data '{
  10. "name":"error"
  11. }'
  12. {"code":400,"msg":"dummy error","data":{}}

::tip hint
Here is only a demonstration of the usability of httpx.SetErrorHandler , refer to Unified Response Format : :::