2016-10-20 20:30:53 +02:00
|
|
|
+++
|
|
|
|
title = "Error Handling"
|
|
|
|
description = "Error handling in Echo"
|
2016-11-21 00:16:22 +02:00
|
|
|
[menu.main]
|
2016-10-20 20:30:53 +02:00
|
|
|
name = "Error Handling"
|
|
|
|
parent = "guide"
|
|
|
|
weight = 8
|
|
|
|
+++
|
|
|
|
|
|
|
|
Echo advocates centralized HTTP error handling by returning error from middleware
|
|
|
|
or handlers.
|
|
|
|
|
|
|
|
- Log errors from a unified location
|
|
|
|
- Send customized HTTP responses
|
|
|
|
|
|
|
|
For example, when basic auth middleware finds invalid credentials it returns
|
|
|
|
`401 - Unauthorized` error, aborting the current HTTP request.
|
|
|
|
|
|
|
|
```go
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/labstack/echo"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
e := echo.New()
|
2016-11-05 21:35:33 +02:00
|
|
|
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
2016-10-26 01:56:12 +02:00
|
|
|
return func(c echo.Context) error {
|
2016-11-05 21:35:33 +02:00
|
|
|
// Extract the credentials from HTTP request header and perform a security
|
|
|
|
// check
|
|
|
|
|
|
|
|
// For invalid credentials
|
2016-10-26 01:56:12 +02:00
|
|
|
return echo.NewHTTPError(http.StatusUnauthorized)
|
2016-11-05 21:35:33 +02:00
|
|
|
|
|
|
|
// For valid credentials call next
|
|
|
|
// return next(c)
|
2016-10-26 01:56:12 +02:00
|
|
|
}
|
2016-10-20 20:30:53 +02:00
|
|
|
})
|
2016-11-05 21:35:33 +02:00
|
|
|
e.GET("/", welcome)
|
2016-11-18 02:21:41 +02:00
|
|
|
e.Logger.Fatal(e.Start(":1323"))
|
2016-10-20 20:30:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func welcome(c echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "Welcome!")
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
See how [HTTPErrorHandler](/guide/customization#http-error-handler) handles it.
|