How to print details of a 'catch all' exception in Swift?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Swift error handling is type-safe, but in real apps you still need a fallback when an unexpected error reaches a broad catch. A good catch-all block should log enough detail for debugging without leaking sensitive data. This guide shows a practical pattern for printing rich error details from a catch-all handler.
Catch Order and Error Shape
In Swift, catch blocks are evaluated top to bottom. Put specific errors first, then a final catch-all block for everything else.
The final catch receives an Error value. That is enough for baseline logging, but we can improve it.
Bridge to NSError for Domain and Code
Most Swift and Foundation errors can be bridged to NSError, which exposes domain, code, and userInfo. These fields are valuable during triage.
This is a production-friendly base because it logs structured details and remains simple.
Add Lightweight Debug Context
Logging raw errors is useful, but context makes logs actionable. Include operation name, user-safe identifiers, and call stack in debug builds.
Use this style in development and route it through your logging framework in production.
Differentiate Display Errors and Diagnostic Errors
Users should not see raw diagnostic details. Keep two paths: one for logs and one for UI messaging.
This prevents accidental exposure of internals while still giving developers enough information.
Structured Logging With Logger
Plain print calls are fine for local debugging, but production apps benefit from structured logs. Apple platforms provide Logger through the os module, which integrates with Console and log filtering tools.
Use privacy controls deliberately. Non-sensitive fields can be public, while user data should stay private or redacted. This approach gives better observability without sacrificing safety.
Common Pitfalls
A frequent mistake is only printing localizedDescription and ignoring domain or code, which removes useful grouping signals in logs. Another mistake is catching everything too early and swallowing errors before higher layers can recover. Teams also often dump full userInfo in release logs, which may include sensitive values. If you log it, scrub secrets and tokens first. Finally, avoid relying on crash-only visibility. Structured error logs from catch-all handlers are often the fastest path to root cause.
Summary
- Put specific catches first, then keep a final catch-all block.
- Bridge
ErrortoNSErrorto log domain, code, anduserInfo. - Attach operation context so logs are actionable.
- Separate developer diagnostics from user-facing messages.
- Scrub sensitive values before persisting logs in production.

