Fiber Error Handler: Panic Recovery vs Custom
In this tutorial, you'll learn about Fiber Error Handler: Panic Recovery vs Custom. We cover key concepts, practical examples, and best practices.
Error handling in Fiber -- Recover from panics and return structured errors using custom error handlers and recovery middleware.
The Problem
Fiber recovers from panics only if the Recover middleware is registered. Without it, a panic crashes the server. Fiber also supports custom error handlers.
Wrong
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
panic("something went wrong")
})
Output:
$ curl http://localhost:8080/
// Server crashes with panic
Right
app := fiber.New(fiber.Config{
ErrorHandler: func(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
if e, ok := err.(*fiber.Error); ok { code = e.Code }
return c.Status(code).JSON(fiber.Map{"error": err.Error()})
},
})
app.Use(recover.New())
Output:
$ curl http://localhost:8080/
{"error":"Not Found"}
Prevention
- Always add recover.New() middleware
- Set a custom ErrorHandler in fiber.Config
- Return fiber.ErrNotFound for 404s
- Log errors before returning
- Differentiate validation, auth, server errors
Common Mistakes with fiber error handler
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro