Skip to main content

Overview

The recovery system provides automatic panic recovery for HTTP requests with proper error responses and detailed logging.

Functions

RecoverFromPanic

Recovers from panics and returns a structured 500 error response.
core.App
required
PocketBase application for logging
*core.RequestEvent
required
Request event where panic occurred
Location: core/logging/error_handler.go:152 Behavior:
  1. Captures panic with recover()
  2. Logs panic with trace ID and stack trace
  3. Excludes static file requests from panic logs
  4. Returns HTML error page for browsers
  5. Returns JSON error response for API requests
Example Usage:

SetupRecovery

Configures global panic recovery middleware.
core.App
required
PocketBase application
*core.ServeEvent
required
ServeEvent to bind recovery middleware
Location: core/logging/logging.go:227 Example:

Error Response Type

Location: 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
Browser Requests:
  • Return HTML for browsers (Mozilla, Chrome, Safari, Firefox)
  • Return HTML when Accept: text/html header is present
  • Return JSON for all other clients
Location: 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
Location: core/logging/error_handler.go:157

Stack Trace Capture

The recovery system captures full stack traces using runtime/debug.Stack():
Location: core/logging/error_handler.go:164

Best Practices

  1. Global Setup: Use SetupRecovery() once during app initialization
  2. Don’t Suppress: Let panics propagate to recovery middleware, don’t silently recover
  3. Log Context: Include trace IDs and request context in panic logs
  4. Resource Cleanup: Use deferred cleanup before panic recovery
  5. Monitor Panics: Set up alerting for production panics
  6. Fix Root Cause: Panics indicate bugs - fix them, don’t just recover
  7. Testing: Test panic scenarios to ensure graceful degradation

Common Panic Scenarios

Nil Pointer Dereference

Index Out of Bounds

Type Assertion