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.
app.Get("/", func(c *fiber.Ctx) error {// Pass error to Fiberreturn c.SendFile("file-does-not-exist")})
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:
Examplepackage mainβimport ("github.com/gofiber/fiber/v2""github.com/gofiber/fiber/v2/middleware/recover")βfunc main() {app := fiber.New()βapp.Use(recover.New())βapp.Get("/", func(c *fiber.Ctx) error {panic("This panic is catched by fiber")})βlog.Fatal(app.Listen(":3000"))}
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
).
Exampleapp.Get("/", func(c *fiber.Ctx) error {// 503 Service Unavailablereturn fiber.ErrServiceUnavailableβ// 503 On vacation!return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")})
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.
Example// Default error handlervar DefaultErrorHandler = func(c *fiber.Ctx, err error) error {// Default 500 statuscodecode := fiber.StatusInternalServerErrorβif e, ok := err.(*fiber.Error); ok {// Override status code if fiber.Error typecode = e.Code}// Set Content-Type: text/plain; charset=utf-8c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)β// Return statuscode with error messagereturn c.Status(code).SendString(err.Error())}
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.
Example// Create a new fiber instance with custom configapp := fiber.New(fiber.Config{// Override default error handlerErrorHandler: func(ctx *fiber.Ctx, err error) error {// Statuscode defaults to 500code := fiber.StatusInternalServerErrorβ// Retreive the custom statuscode if it's an fiber.*Errorif e, ok := err.(*fiber.Error); ok {code = e.Code}β// Send custom error pageerr = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))if err != nil {// In case the SendFile failsreturn ctx.Status(500).SendString("Internal Server Error")}β// Return from handlerreturn nil},})β// ...
Special thanks to the Echo & Express framework for inspiration regarding error handling.