Lightning gives you three complementary tools for error handling: a configurable not-found handler, the Recovery() middleware for panics, and ctx.JSONError() for returning structured error responses from your handlers.
Custom 404 Handler
By default, unmatched routes return 404 Not Found as plain text. Override this by passing a NotFoundHandler in your config to lightning.NewApp().
The not-found handler runs after the global middleware chain, so any middleware you register with app.Use() also applies to 404 responses.
Recovery Middleware
Recovery() catches any panic in a downstream handler or middleware and writes a 500 response instead of crashing the server. It also prints the panic value and stack trace to stderr.
Default behavior
The built-in handler responds with 500 Internal Server Error as plain text.
Custom panic handler
Pass your own handler to override the default response:
Recovery() accepts at most one custom handler. The panic value and stack trace are always written to stderr regardless of which handler is active.
Programmatic Error Responses
Use ctx.JSONError(code, message) to return a JSON error from any handler. The HTTP status code and the code field in the body are set to the same value.
Response body for the unauthorized case:
Complete Example: Custom 404 and 500 Handlers
Test the handlers: