Error Handling

Echo advocates centralized HTTP error handling by returning error from middleware and handlers. It allows us to log/report errors to external services from a unified location and send customized HTTP responses.

For example, when basic auth middleware finds invalid credentials it returns 401 - Unauthorized error, aborting the current HTTP request.

package main

import (


func main() {
	e := echo.New()
	e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// Extract the credentials from HTTP request header and perform a security
			// check

			// For invalid credentials
			return echo.NewHTTPError(http.StatusUnauthorized)

			// For valid credentials call next
			// return next(c)
	e.GET("/", welcome)

func welcome(c echo.Context) error {
	return c.String(http.StatusOK, "Welcome!")

See how HTTPErrorHandler handles it.