Overview
The recovery system provides automatic panic recovery for HTTP requests with proper error responses and detailed logging.Functions
RecoverFromPanic
core.App
required
PocketBase application for logging
*core.RequestEvent
required
Request event where panic occurred
core/logging/error_handler.go:152
Behavior:
- Captures panic with
recover() - Logs panic with trace ID and stack trace
- Excludes static file requests from panic logs
- Returns HTML error page for browsers
- Returns JSON error response for API requests
SetupRecovery
core.App
required
PocketBase application
*core.ServeEvent
required
ServeEvent to bind recovery middleware
core/logging/logging.go:227
Example:
Error Response Type
core/logging/error_handler.go:20
Response Formats
JSON Response (API Routes)
HTML Response (Browser Requests)
Returns a styled HTML error page with:- Error status and message
- Error type and operation
- Trace ID for debugging
- Timestamp
Content Negotiation
The recovery system automatically detects the appropriate response format: API Routes (/api/*):
- Always return JSON
- Regardless of Accept header or User-Agent
- Return HTML for browsers (Mozilla, Chrome, Safari, Firefox)
- Return HTML when
Accept: text/htmlheader is present - Return JSON for all other clients
core/logging/error_handler.go:179
Panic Log Format
Complete Examples
Global Recovery Setup
Manual Recovery in Handler
Custom Recovery with Cleanup
Recovery with Alerting
Testing Panic Recovery
Excluded Paths
Panic logs are suppressed for these paths to reduce noise:/service-worker.js/favicon.ico/manifest.json/robots.txt- Files ending in:
.map,.ico,.webmanifest
core/logging/error_handler.go:157
Stack Trace Capture
The recovery system captures full stack traces usingruntime/debug.Stack():
core/logging/error_handler.go:164
Best Practices
- Global Setup: Use
SetupRecovery()once during app initialization - Don’t Suppress: Let panics propagate to recovery middleware, don’t silently recover
- Log Context: Include trace IDs and request context in panic logs
- Resource Cleanup: Use deferred cleanup before panic recovery
- Monitor Panics: Set up alerting for production panics
- Fix Root Cause: Panics indicate bugs - fix them, don’t just recover
- Testing: Test panic scenarios to ensure graceful degradation
Common Panic Scenarios
Nil Pointer Dereference
Index Out of Bounds
Type Assertion
Related
- Logging - Structured logging system
- Error Handler - Error handling middleware
- Monitoring - System health monitoring