description
Fiber supports centralized error handling by passing an error argument into the Next method which allows you to log errors to external services or send a customized HTTP response to the client.

🐛 Error Handling

Catching Errors

It’s essential to ensure that Fiber catches all errors that occur while running route handlers and middleware. You must pass them to the ctx.Next() function, where Fiber will catch and process them.

  1. app.Get("/", func(c *fiber.Ctx) {
  2. err := c.SendFile("file-does-not-exist")
  3. if err != nil {
  4. c.Next(err) // Pass error to Fiber
  5. }
  6. })

Fiber does not handle panics by default. To recover from a panic thrown by any handler in the stack, you need to include the Recover middleware below:

  1. package main
  2. import (
  3. "github.com/gofiber/fiber"
  4. "github.com/gofiber/fiber/middleware"
  5. )
  6. func main() {
  7. app := fiber.New()
  8. app.Use(middleware.Recover())
  9. app.Get("/", func(c *fiber.Ctx) {
  10. panic("This panic is catched by the ErrorHandler")
  11. })
  12. log.Fatal(app.Listen(3000))
  13. }

Because ctx.Next() accepts an error interface, you could use Fiber’s custom error struct to pass an additional status code using fiber.NewError(). It’s optional to pass a message; if this is left empty, it will default to the status code message (404 equals Not Found).

  1. app.Get("/", func(c *fiber.Ctx) {
  2. err := fiber.NewError(503)
  3. c.Next(err) // 503 Service Unavailable
  4. err := fiber.NewError(404, "Sorry, not found!")
  5. c.Next(err) // 404 Sorry, not found!
  6. })

Default Error Handler

Fiber provides an error handler by default. For a standard error, the response is sent as 500 Internal Server Error. If error is of type fiber*Error, response is sent with the provided status code and message.

  1. // Default error handler
  2. app.Settings.ErrorHandler = func(ctx *fiber.Ctx, err error) {
  3. // Statuscode defaults to 500
  4. code := fiber.StatusInternalServerError
  5. // Check if it's an fiber.Error type
  6. if e, ok := err.(*fiber.Error); ok {
  7. code = e.Code
  8. }
  9. // Return HTTP response
  10. ctx.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
  11. ctx.Status(code).SendString(err.Error())
  12. }

Custom Error Handler

A custom error handler can be set via app.Settings.ErrorHandler

In most cases, the default error handler should be sufficient. However, a custom error handler can come in handy if you want to capture different types of errors and take action accordingly e.g., send a notification email or log an error to the centralized system. You can also send customized responses to the client e.g., error page or just a JSON response.

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

  1. app := fiber.New()
  2. // Custom error handler
  3. app.Settings.ErrorHandler = func(ctx *fiber.Ctx, err error) {
  4. // Statuscode defaults to 500
  5. code := fiber.StatusInternalServerError
  6. // Retreive the custom statuscode if it's an fiber.*Error
  7. if e, ok := err.(*fiber.Error); ok {
  8. code = e.Code
  9. }
  10. // Send custom error page
  11. err = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))
  12. if err != nil {
  13. ctx.Status(500).SendString("Internal Server Error")
  14. }
  15. }

Special thanks to the Echo & Express framework for inspiration regarding error handling.