2015-10-02 03:24:38 +02:00
|
|
|
---
|
|
|
|
title: Error Handling
|
|
|
|
menu:
|
2015-10-08 22:54:31 +02:00
|
|
|
side:
|
2015-10-02 03:24:38 +02:00
|
|
|
parent: guide
|
2015-10-06 00:52:07 +02:00
|
|
|
weight: 7
|
2015-10-02 03:24:38 +02:00
|
|
|
---
|
|
|
|
|
|
|
|
Echo advocates centralized HTTP error handling by returning `error` from middleware
|
|
|
|
and handlers.
|
|
|
|
|
2015-10-03 04:48:47 +02:00
|
|
|
It allows you to:
|
2015-10-02 03:24:38 +02:00
|
|
|
|
|
|
|
- Debug by writing stack trace to the HTTP response.
|
|
|
|
- Customize HTTP responses.
|
|
|
|
- Recover from panics inside middleware or handlers.
|
|
|
|
|
|
|
|
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()
|
|
|
|
e.Use(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)
|
|
|
|
})
|
|
|
|
e.Get("/welcome", welcome)
|
|
|
|
e.Run(":1323")
|
|
|
|
}
|
|
|
|
|
|
|
|
func welcome(c *echo.Context) error {
|
|
|
|
return c.String(http.StatusOK, "Welcome!")
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2015-10-03 04:48:47 +02:00
|
|
|
See how [HTTPErrorHandler](/guide/customization#http-error-handler) handles it.
|