Skip to content

Echo Error Handler: Default vs Custom

DodaTech Updated 2026-06-24 1 min read

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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

**Does Echo have a default JSON error handler?**

No. The default returns HTML. You must set a custom HTTPErrorHandler.

How do I differentiate client vs server errors?

Check httpErr.Code. 4xx = client, 5xx = server.

Can I use templates for error pages?

Yes. Call c.Render() inside the error handler.


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