Skip to content

Commit ed51400

Browse files
committed
Enhanced default http error handler
Signed-off-by: Vishal Rana <[email protected]>
1 parent 87da9a9 commit ed51400

File tree

2 files changed

+16
-20
lines changed

2 files changed

+16
-20
lines changed

echo.go

+15-19
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,9 @@ type (
9999

100100
// HTTPError represents an error that occurred while handling a request.
101101
HTTPError struct {
102-
Code int
103-
Message interface{}
104-
Internal error // Stores the error returned by an external dependency
102+
Code int `json:"code"`
103+
Message interface{} `json:"message"`
104+
Internal error `json:"-"` // Stores the error returned by an external dependency
105105
}
106106

107107
// MiddlewareFunc defines a function to process middleware.
@@ -341,32 +341,28 @@ func (e *Echo) Routers() map[string]*Router {
341341
// DefaultHTTPErrorHandler is the default HTTP error handler. It sends a JSON response
342342
// with status code.
343343
func (e *Echo) DefaultHTTPErrorHandler(err error, c Context) {
344-
var (
345-
code = http.StatusInternalServerError
346-
msg interface{}
347-
)
348-
349-
if he, ok := err.(*HTTPError); ok {
350-
code = he.Code
351-
msg = he.Message
344+
he, ok := err.(*HTTPError)
345+
if ok {
352346
if he.Internal != nil {
353347
err = fmt.Errorf("%v, %v", err, he.Internal)
354348
}
355-
} else if e.Debug {
356-
msg = err.Error()
357349
} else {
358-
msg = http.StatusText(code)
350+
he = &HTTPError{
351+
Code: http.StatusInternalServerError,
352+
}
359353
}
360-
if _, ok := msg.(string); ok {
361-
msg = Map{"message": msg}
354+
if e.Debug {
355+
he.Message = err.Error()
356+
} else {
357+
he.Message = http.StatusText(he.Code)
362358
}
363359

364360
// Send response
365361
if !c.Response().Committed {
366362
if c.Request().Method == http.MethodHead { // Issue #608
367-
err = c.NoContent(code)
363+
err = c.NoContent(he.Code)
368364
} else {
369-
err = c.JSON(code, msg)
365+
err = c.JSON(he.Code, he)
370366
}
371367
if err != nil {
372368
e.Logger.Error(err)
@@ -749,7 +745,7 @@ func NewHTTPError(code int, message ...interface{}) *HTTPError {
749745

750746
// Error makes it compatible with `error` interface.
751747
func (he *HTTPError) Error() string {
752-
return fmt.Sprintf("code=%d, message=%v", he.Code, he.Message)
748+
return fmt.Sprintf("code=%d, message=%v, internal=%v", he.Code, he.Message, he.Internal)
753749
}
754750

755751
// SetInternal sets error to HTTPError.Internal

echo_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ func TestHTTPError(t *testing.T) {
534534
err := NewHTTPError(http.StatusBadRequest, map[string]interface{}{
535535
"code": 12,
536536
})
537-
assert.Equal(t, "code=400, message=map[code:12]", err.Error())
537+
assert.Equal(t, "code=400, message=map[code:12], internal=<nil>", err.Error())
538538
}
539539

540540
func TestEchoClose(t *testing.T) {

0 commit comments

Comments
 (0)