Panic Recovery
Handle panics from route handlers safely using a custom recovery handler and fail-safe internal recovery.
The router package can recover from panics that occur inside route handlers.
This allows the server to keep running and return a controlled response instead of crashing the application process.
Recovery is useful for:
- preventing unexpected handler panics from terminating the server
- returning custom
500 Internal Server Errorresponses - logging panic details
- keeping production services available during unexpected failures
Custom Recovery Handler
Register a custom recovery handler using r.Recovery.
r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Custom Internal Server Error"))
})This handler is executed whenever a panic occurs inside a route handler.
Example
package main
import (
"log/slog"
"net/http"
"os"
"github.com/netlifeguru/router"
)
func main() {
r := router.New()
r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Custom Internal Server Error: Don't worry, we caught the panic!"))
})
r.HandleFunc("/", "ANY", func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
panic("Something went terribly wrong")
})
if err := r.ListenAndServe(":8000"); err != nil {
slog.Error("failed to start server", "error", err)
os.Exit(1)
}
}Run the application:
go run .Test the route:
curl http://localhost:8000/Expected response:
Custom Internal Server Error: Don't worry, we caught the panic!Fail-Safe Recovery
The router also protects the recovery handler itself.
If the custom recovery handler panics, the router catches that panic as well and returns a standard internal server error response.
This prevents a broken recovery handler from crashing or hanging the application.
Example:
r.Recovery(func(w http.ResponseWriter, req *http.Request, ctx *router.Context) {
panic("recovery handler failed")
})In this case, the router falls back to a safe 500 Internal Server Error response.
Panic Logging
When a panic occurs, the router logs the panic through Go’s standard log/slog package.
If a custom logger such as github.com/netlifeguru/logger is configured, panic logs follow the active logger configuration.
This means panic logs can be written to:
- terminal output
- structured JSON files
- rotated log files
- any custom
slog.Handler
Notes
Recovery only handles panics that occur during request handling.
It does not replace normal error handling for expected application errors. Use explicit error responses for known validation, authorization, or business logic failures.