mirror of
https://github.com/zap-proto/fiber.git
synced 2026-10-30 15:06:23 +00:00
2.4 KiB
2.4 KiB
id
| id |
|---|
| recover |
Recover
The Recover middleware for Fiber intercepts panics and forwards them to the central ErrorHandler.
Signatures
func New(config ...Config) fiber.Handler
Examples
Import the middleware package:
import (
"github.com/gofiber/fiber/v3"
recoverer "github.com/gofiber/fiber/v3/middleware/recover"
)
Once your Fiber app is initialized, use the middleware like this:
// Initialize default config
app.Use(recoverer.New())
// Panics in subsequent handlers are caught by the middleware
app.Get("/", func(c fiber.Ctx) error {
panic("I'm an error")
})
Config
| Property | Type | Description | Default |
|---|---|---|---|
| Next | func(fiber.Ctx) bool |
Skip when the function returns true. |
nil |
| PanicHandler | func(fiber.Ctx, any) error |
Customize the error returned from a recovered panic. | DefaultPanicHandler |
| EnableStackTrace | bool |
Capture and include a stack trace in error responses. | false |
| StackTraceHandler | func(fiber.Ctx, any) |
Handle the captured stack trace when enabled. | defaultStackTraceHandler |
Default Config
var ConfigDefault = recoverer.Config{
Next: nil,
PanicHandler: DefaultPanicHandler,
StackTraceHandler: defaultStackTraceHandler,
EnableStackTrace: false,
}
// Set up a PanicHandler to hide internals.
app.Use(recoverer.New(recoverer.Config{PanicHandler: func(c fiber.Ctx, r any) error {
return fiber.ErrInternalServerError
}}))
// In more elaborate scenarios you can also create a custom error which can be processed differently in the fiber.ErrorHandler.
// See the tests for an example of such an ErrorHandler.
// You could also just wrap the default handler's error, e.g. fmt.Errorf("[RECOVERED]: %w", recoverer.DefaultPanicHandler(c, r))
app.Use(recoverer.New(recoverer.Config{PanicHandler: func(c fiber.Ctx, r any) error {
return &MyCustomRecoveredFromPanicError {
Inner: recoverer.DefaultPanicHandler(c, r),
}
}}))