echo icon indicating copy to clipboard operation
echo copied to clipboard

Custom middleware to handle error doesn't work when using return echo.NewHTTPError

Open MGMehdi opened this issue 3 months ago • 2 comments

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

MGMehdi avatar Sep 11 '25 17:09 MGMehdi

https://echo.labstack.com/docs/error-handling

hellocashmere avatar Sep 12 '25 13:09 hellocashmere

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))

jean0t avatar Dec 03 '25 12:12 jean0t