02 / 04

When should you use panic and recover vs returning errors?

Use panic only for unrecoverable programmer errors and invariant violations. Use recover at process boundaries like HTTP handlers to prevent one request from crashing the server. Never use panic for expected business errors.

Panic and recover patterns
Guidelines
  1. 1

    Panic: nil pointer dereference, index out of bounds, type assertion on wrong type (programmer errors)

  2. 2

    Panic in init() functions is acceptable — startup misconfiguration should be fatal

  3. 3

    Recover should only be used at package/process boundaries — never silently swallow panics

  4. 4

    After recover, log a full stack trace and decide: return error to caller, or restart the operation

  5. 5

    Libraries should never panic for expected conditions — only the application layer should use panic/recover