dongweihuai5601 2019-04-04 10:02
浏览 92
已采纳

如何重写DefaultHTTPErrorHandler格式的消息

I'm using the Echo framework.

How can I change this format response to my own format its error from JWT Library https://github.com/dgrijalva/jwt-go

{
  "message": "invalid or expired jwt"
}

i want to change something like this

{
  "meta": {
    "status": false,
    "message": "Unauthorized",
    "messages": null
  },
  "result": null
}

i cant find how to do it to override DefaultHTTPErrorHandler

this customHttpErrorHandler

    e := echo.New()
    e.HTTPErrorHandler = func(err error, c echo.Context) {
        var (
            code = http.StatusInternalServerError
            msg  interface{}
        )

        type (
            Map map[string]interface{}
        )

        if he, ok := err.(*echo.HTTPError); ok {
            code = he.Code
            msg = he.Message
            if he.Internal != nil {
                err = fmt.Errorf("%v, %v", err, he.Internal)
            }
        } else if e.Debug {
            msg = err.Error()
        } else {
            msg = http.StatusText(code)
        }

        if _, ok := msg.(string); ok {
            msg = Map{"sempak": msg}
        }

        // Send response
        if !c.Response().Committed {
            if c.Request().Method == http.MethodHead {
                err = c.NoContent(code)
            } else {
                err = c.JSON(code, msg)
            }
            if err != nil {
                e.Logger.Error(err)
            }
        }
    }
  • 写回答

1条回答 默认 最新

  • du1913 2019-04-04 10:21
    关注

    First you need to catch the error from the JWT library. Here you can find an example (ExampleParse_errorChecking) how to do this.

    When you know the error you can return your custom response or use Custom HTTP Error Handler see details here

    Custom HTTP error handler can be set via e.HTTPErrorHandler

    func customHTTPErrorHandler(err error, c echo.Context) {
        // ...
    }
    
    e.HTTPErrorHandler = customHTTPErrorHandler
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序