DefaultHTTPErrorHandler creates new default HTTP error handler implementation. It sends a JSON response with status code. `exposeError` parameter decides if returned message will contain also error message or not Note: DefaultHTTPErrorHandler does not log errors. Use middleware for it if errors nee
(exposeError bool)
| 429 | // handler. Then the error that global error handler received will be ignored because we have already "committed" the |
| 430 | // response and status code header has been sent to the client. |
| 431 | func DefaultHTTPErrorHandler(exposeError bool) HTTPErrorHandler { |
| 432 | return func(c *Context, err error) { |
| 433 | if r, _ := UnwrapResponse(c.response); r != nil && r.Committed { |
| 434 | return |
| 435 | } |
| 436 | |
| 437 | code := http.StatusInternalServerError |
| 438 | var sc HTTPStatusCoder |
| 439 | if errors.As(err, &sc) { |
| 440 | if tmp := sc.StatusCode(); tmp != 0 { |
| 441 | code = tmp |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | var result any |
| 446 | switch m := sc.(type) { |
| 447 | case json.Marshaler: // this type knows how to format itself to JSON |
| 448 | result = m |
| 449 | case *HTTPError: |
| 450 | sText := m.Message |
| 451 | if sText == "" { |
| 452 | sText = http.StatusText(code) |
| 453 | } |
| 454 | msg := map[string]any{"message": sText} |
| 455 | if exposeError { |
| 456 | if wrappedErr := m.Unwrap(); wrappedErr != nil { |
| 457 | msg["error"] = wrappedErr.Error() |
| 458 | } |
| 459 | } |
| 460 | result = msg |
| 461 | default: |
| 462 | msg := map[string]any{"message": http.StatusText(code)} |
| 463 | if exposeError { |
| 464 | msg["error"] = err.Error() |
| 465 | } |
| 466 | result = msg |
| 467 | } |
| 468 | |
| 469 | var cErr error |
| 470 | if c.Request().Method == http.MethodHead { // Issue #608 |
| 471 | cErr = c.NoContent(code) |
| 472 | } else { |
| 473 | cErr = c.JSON(code, result) |
| 474 | } |
| 475 | if cErr != nil { |
| 476 | c.Logger().Error("echo default error handler failed to send error to client", "error", cErr) // truly rare case. ala client already disconnected |
| 477 | } |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | // Pre adds middleware to the chain which is run before router tries to find matching route. |
| 482 | // Meaning middleware is executed even for 404 (not found) cases. |
searching dependent graphs…