Skip to content

Commit 5888bc1

Browse files
author
Mario de Frutos
committed
Add status code to error handler to be able to send 4xx errors too for example
1 parent e3dc3c3 commit 5888bc1

File tree

3 files changed

+8
-7
lines changed

3 files changed

+8
-7
lines changed

context.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ func (c *Context) NoContent(code int) error {
8080
}
8181

8282
// Error invokes the registered HTTP error handler.
83-
func (c *Context) Error(err error) {
84-
c.echo.httpErrorHandler(err, c)
83+
func (c *Context) Error(err error, code int) {
84+
c.echo.httpErrorHandler(err, code, c)
8585
}
8686

8787
// Get retrieves data from the context.

echo.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ type (
3434
HandlerFunc func(*Context) error
3535

3636
// HTTPErrorHandler is a centralized HTTP error handler.
37-
HTTPErrorHandler func(error, *Context)
37+
HTTPErrorHandler func(error, int, *Context)
3838

3939
BindFunc func(*http.Request, interface{}) error
4040

@@ -122,11 +122,11 @@ func New() (e *Echo) {
122122
e.NotFoundHandler(func(c *Context) {
123123
http.Error(c.Response, http.StatusText(http.StatusNotFound), http.StatusNotFound)
124124
})
125-
e.HTTPErrorHandler(func(err error, c *Context) {
125+
e.HTTPErrorHandler(func(err error, code int, c *Context) {
126126
if err != nil {
127127
// TODO: Warning
128128
log.Printf("echo: %s", color.Yellow("http error handler not registered"))
129-
http.Error(c.Response, err.Error(), http.StatusInternalServerError)
129+
http.Error(c.Response, err.Error(), code)
130130
}
131131
})
132132
e.Binder(func(r *http.Request, v interface{}) error {
@@ -303,7 +303,7 @@ func (e *Echo) ServeHTTP(w http.ResponseWriter, r *http.Request) {
303303

304304
// Execute chain
305305
if err := h(c); err != nil {
306-
e.httpErrorHandler(err, c)
306+
e.httpErrorHandler(err, http.StatusInternalServerError, c)
307307
}
308308

309309
e.pool.Put(c)

middleware/logger.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"log"
5+
"net/http"
56
"time"
67

78
"github.com/labstack/echo"
@@ -12,7 +13,7 @@ func Logger(h echo.HandlerFunc) echo.HandlerFunc {
1213
return func(c *echo.Context) error {
1314
start := time.Now()
1415
if err := h(c); err != nil {
15-
c.Error(err)
16+
c.Error(err, http.StatusInternalServerError)
1617
}
1718
end := time.Now()
1819
m := c.Request.Method

0 commit comments

Comments
 (0)