Recover Middleware¶
Catches panics and returns a 500 Internal Server Error instead of crashing the server.
Usage¶
Basic Usage¶
With Configuration¶
app.Use(middleware.RecoverWithConfig(middleware.RecoverConfig{
LogPanics: true,
OnPanic: func(c *marten.Ctx, err any) error {
return c.JSON(500, marten.M{
"error": "internal error",
"request_id": c.RequestID(),
})
},
}))
JSON Error Response¶
Configuration¶
| Option | Type | Description |
|---|---|---|
LogPanics | bool | Log panics to stdout (default: true) |
OnPanic | func(*Ctx, any) error | Custom panic handler |
Behavior¶
When a panic occurs:
- The panic is caught
- The error is logged
- A 500 response is returned
- The server continues running
Example¶
package main
import (
"github.com/gomarten/marten"
"github.com/gomarten/marten/middleware"
)
func main() {
app := marten.New()
app.Use(middleware.Recover)
app.GET("/panic", func(c *marten.Ctx) error {
panic("something went wrong!")
return nil
})
app.Run(":3000")
}
Request to /panic returns:
Log Output¶
Custom Recovery¶
With Custom Handler¶
app.Use(middleware.RecoverWithHandler(func(c *marten.Ctx, err any) error {
// Log with stack trace
log.Printf("panic: %v\n%s", err, debug.Stack())
// Custom response
return c.JSON(500, marten.M{
"error": "internal error",
"request_id": c.RequestID(),
})
}))
JSON Response¶
Returns:
Full Custom Recovery¶
For more control, create your own middleware:
func CustomRecover(next marten.Handler) marten.Handler {
return func(c *marten.Ctx) (err error) {
defer func() {
if r := recover(); r != nil {
// Log with stack trace
log.Printf("panic: %v\n%s", r, debug.Stack())
// Custom response
err = c.JSON(500, marten.M{
"error": "internal error",
"request_id": c.RequestID(),
})
}
}()
return next(c)
}
}
Best Practices¶
- Always use Recover - Prevents server crashes
- Place early in middleware chain - Catches panics from all handlers
- Log panics - For debugging
- Don't expose panic details - Security risk