description: >- Fiber supports centralized error handling by returning an error to the handler 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 return them to the handler function, where Fiber will catch and process them.

  1. app.Get("/", func(c *fiber.Ctx) error {
  2. // Pass error to Fiber
  3. return c.SendFile("file-does-not-exist")
  4. })

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/v2"
  4. "github.com/gofiber/fiber/v2/middleware/recover"
  5. )
  6. func main() {
  7. app := fiber.New()
  8. app.Use(recover.New())
  9. app.Get("/", func(c *fiber.Ctx) error {
  10. panic("This panic is caught by fiber")
  11. })
  12. log.Fatal(app.Listen(":3000"))
  13. }

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) error {
  2. // 503 Service Unavailable
  3. return fiber.ErrServiceUnavailable
  4. // 503 On vacation!
  5. return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
  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 the error is of type fiber.Error, the response is sent with the provided status code and message.

  1. // Default error handler
  2. var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
  3. // Default 500 statuscode
  4. code := fiber.StatusInternalServerError
  5. if e, ok := err.(*fiber.Error); ok {
  6. // Override status code if fiber.Error type
  7. code = e.Code
  8. }
  9. // Set Content-Type: text/plain; charset=utf-8
  10. c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
  11. // Return statuscode with error message
  12. return c.Status(code).SendString(err.Error())
  13. }

Custom Error Handler

A custom error handler can be set using a Config when initializing a Fiber instance.

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. // Create a new fiber instance with custom config
  2. app := fiber.New(fiber.Config{
  3. // Override default error handler
  4. ErrorHandler: func(ctx *fiber.Ctx, err error) error {
  5. // Status code defaults to 500
  6. code := fiber.StatusInternalServerError
  7. // Retrieve the custom status code if it's an fiber.*Error
  8. if e, ok := err.(*fiber.Error); ok {
  9. code = e.Code
  10. }
  11. // Send custom error page
  12. err = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))
  13. if err != nil {
  14. // In case the SendFile fails
  15. return ctx.Status(500).SendString("Internal Server Error")
  16. }
  17. // Return from handler
  18. return nil
  19. },
  20. })
  21. // ...

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