Error Handling

Ensuring that Fiber captures all errors that occur while running route handlers and middleware is crucial. You must return them to the handler function for Fiber to capture and process them.

  • Example
app.Get("/", func(c *fiber.Ctx) error {
    // Pass the error to Fiber
    return c.SendFile("file-does-not-exist")
})

By default, Fiber does not handle panic errors. To recover from any panic thrown by handlers in the stack and avoid crashing the Go program, you need to include the Recover middleware as shown below:

  • Example
package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
    app := fiber.New()

    // Use the recover middleware to catch panic errors
    app.Use(recover.New())

    app.Get("/", func(c *fiber.Ctx) error {
        panic("This panic is caught by fiber")
    })

    log.Fatal(app.Listen(":3000"))
}

You can use Fiber’s custom error structure with fiber.NewError() to pass additional status codes. Passing a message is optional; if left empty, it will default to the status code message (e.g., 404 equals Not Found).

  • Example
app.Get("/", func(c *fiber.Ctx) error {
    // 503 Service Unavailable
    return fiber.ErrServiceUnavailable

    // 503 On vacation!
    return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
})

Default Error Handler

Fiber provides a default error handler. For standard errors, the response will be sent as 500 Internal Server Error. If the error type is fiber.Error, the response will be sent using the provided status code and message.

  • Example
// Default error handler
var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
    // Default status code is 500
    code := fiber.StatusInternalServerError

    // If it's *fiber.Error, retrieve the custom status code
    var e *fiber.Error
    if errors.As(err, &e) {
        code = e.Code
    }

    // Set Content-Type: text/plain; charset=utf-8
    c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)

    // Return status code and error message
    return c.Status(code).SendString(err.Error())
}

Custom Error Handler

You can set a custom error handler when initializing the Fiber instance using Config.

In most cases, the default error handler should be sufficient. However, if you want to capture different types of errors and take corresponding actions, such as sending notification emails or logging the errors to a centralized system, then a custom error handler will be very useful. You can also send custom responses to the client, such as error pages or just a JSON response.

The following example shows how to display error pages for different types of errors.

  • Example
// Create a new Fiber instance with custom configuration
app := fiber.New(fiber.Config{
    // Override the default error handler
    ErrorHandler: func(ctx *fiber.Ctx, err error) error {
        // Default status code is 500
        code := fiber.StatusInternalServerError

        // If it's *fiber.Error, retrieve the custom status code
        var e *fiber.Error
        if errors.As(err, &e) {
            code = e.Code
        }

        // Send a custom error page
        err = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))
        if err != nil {
            // If SendFile fails
            return ctx.Status(fiber.StatusInternalServerError).SendString("Internal Server Error")
        }

        // Return from the handler
        return nil
    },
})

// ...