Skip to content

Commit

Permalink
improve error handling for net error(s)
Browse files Browse the repository at this point in the history
fixes: reverse proxy support #2419
  • Loading branch information
ReneWerner87 committed Apr 21, 2023
1 parent ad88630 commit c2f8e14
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 13 deletions.
13 changes: 6 additions & 7 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,12 +470,6 @@ var DefaultMethods = []string{

// DefaultErrorHandler that process return errors from handlers
func DefaultErrorHandler(c *Ctx, err error) error {
var netErr net.Error
if errors.As(err, &netErr) {
// 502 - Bad Gateway
err = ErrBadGateway
}

code := StatusInternalServerError
var e *Error
if errors.As(err, &e) {
Expand Down Expand Up @@ -1054,13 +1048,18 @@ func (app *App) serverErrorHandler(fctx *fasthttp.RequestCtx, err error) {
c := app.AcquireCtx(fctx)
defer app.ReleaseCtx(c)

var errNetOP *net.OpError
var (
errNetOP *net.OpError
netErr net.Error
)

switch {
case errors.As(err, new(*fasthttp.ErrSmallBuffer)):
err = ErrRequestHeaderFieldsTooLarge
case errors.As(err, &errNetOP) && errNetOP.Timeout():
err = ErrRequestTimeout
case errors.As(err, &netErr):
err = ErrBadGateway
case errors.Is(err, fasthttp.ErrBodyTooLarge):
err = ErrRequestEntityTooLarge
case errors.Is(err, fasthttp.ErrGetOnly):
Expand Down
14 changes: 14 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,20 @@ func Test_App_serverErrorHandler_Internal_Error(t *testing.T) {
utils.AssertEqual(t, c.fasthttp.Response.StatusCode(), StatusBadRequest)
}

func Test_App_serverErrorHandler_Network_Error(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
app.serverErrorHandler(c.fasthttp, &net.DNSError{
Err: "test error",
Name: "test host",
IsTimeout: false,
})
utils.AssertEqual(t, string(c.fasthttp.Response.Body()), utils.StatusMessage(StatusBadGateway))
utils.AssertEqual(t, c.fasthttp.Response.StatusCode(), StatusBadGateway)
}

func Test_App_Nested_Params(t *testing.T) {
t.Parallel()
app := New()
Expand Down
6 changes: 0 additions & 6 deletions docs/guide/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,6 @@ Fiber provides an error handler by default. For a standard error, the response i
```go title="Example"
// Default error handler
var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
// Handle internal network errors
var netErr net.Error
if errors.As(err, &netErr) {
// 502 - Bad Gateway
err = ErrBadGateway
}
// Status code defaults to 500
code := fiber.StatusInternalServerError

Expand Down

0 comments on commit c2f8e14

Please sign in to comment.