How to override DefaultHTTPErrorHandler format message

2.1k Views Asked by At

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

There are 1 best solutions below

1
On BEST ANSWER

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