Custom middleware to handle error doesn't work when using return echo.NewHTTPError
Hello,
I've got a controller where I want to return echo.NewHTTPError(http.StatusNotFound, "no stock found")
I've made a custom middleware to handle all error that's working when I have database error, validation etc. I wanted to try using echo.NewHTTPError
I activate the middleware in the main.go like that
// main.go middlewares.ErrorHandlerMiddleware my middleware
e.Use(middleware.Recover(), middleware.RequestID(), middleware.CORS(), middlewares.ErrorHandlerMiddleware)
// middlewares.go
func ErrorHandlerMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
err := next(c)
if err == nil {
return nil
}
return HandleAppError(c, err)
}
}
When I want to use echo.NewHTTPError, the value of err in the middleware is nil.
I don't know what I did wrong. Could you help me ?
Thank you
https://echo.labstack.com/docs/error-handling
the link above solves your issue and comes from the official docs.
echo.NewHTTPError()
You use the NewHTTPError for errors and you call next(c) if there is no error.
the args are: NewHTTPError(HTTP_STATUS (http.Status...), MESSAGE (string))