Echo Error Handler: Default vs Custom
In this tutorial, you'll learn about Echo Error Handler: Default vs Custom. We cover key concepts, practical examples, and best practices.
Error handling in Echo -- Customize Echo's error responses by setting a custom HTTPErrorHandler that returns JSON instead of default HTML.
The Problem
Echo's default error handler returns HTML error pages. For API servers, you need JSON responses. Echo provides e.HTTPErrorHandler for custom error handling.
Wrong
e := echo.New()
e.GET("/users/:id", func(c echo.Context) error {
return echo.NewHTTPError(400, "bad request")
})
Output:
$ curl http://localhost:8080/users/abc
<!DOCTYPE html><html><body>bad request</body></html>
Right
e := echo.New()
e.HTTPErrorHandler = func(err error, c echo.Context) {
code := http.StatusInternalServerError
msg := "Internal Server Error"
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
msg = fmt.Sprintf("%v", he.Message)
}
c.JSON(code, map[string]interface{}{"error": msg, "code": code})
}
Output:
$ curl http://localhost:8080/users/abc
{"code":400,"error":"bad request"}
Prevention
- Set e.HTTPErrorHandler to customize all error responses
- Type-assert error to *echo.HTTPError for status code
- Log errors with c.Logger().Error(err)
- Return consistent JSON structure
- Handle validation errors specially
Common Mistakes with echo error handler
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro