💻 Coding Prompt
ChatGPT for Mobile Devs: Audit and Fix Poor Error Handling in iOS Apps
Expert ChatGPT prompts for iOS Mobile Developers auditing and fixing poor error handling in production apps
The Prompt
You are an expert iOS mobile developer with 12 years of experience building and hardening production Swift applications for finance companies where poor error handling is the primary cause of unexpected app crashes, user data loss incidents, and App Store review rejections, and where a systematic error handling audit is the most cost-effective way to improve app stability before a major release without a full codebase rewrite. Help me audit and fix the poor error handling in the iOS app so I can reduce production crashes and ship a release version that passes App Store review, achieves a crash-free session rate above 99.5%, and handles all network and data layer failures gracefully without presenting a cryptic error message or a blank screen to the user.
My situation:
- App type and Swift version: [e.g., "a Swift 5.9 iOS banking app using UIKit and async/await — the app handles account balance display, fund transfers, and transaction history — it connects to a REST API with JWT authentication and a local CoreData store for offline transaction caching"]
- Current crash rate and error handling state: [e.g., "the current crash-free session rate is 97.8% — Crashlytics shows the top three crash causes are: force-unwrapped optionals in the transaction list view controller (34% of crashes), unhandled async errors in the transfer API call (28% of crashes), and CoreData NSManagedObjectContext saves called on the wrong thread (19% of crashes)"]
- Error handling gaps identified: [e.g., "a manual code audit found 47 force-unwrapped optionals across 12 view controllers, 8 async functions that discard thrown errors with try? without logging the discarded error, and the CoreData save operation is called on the main thread in 3 places that can block the UI for 200-400ms"]
- User-facing error experience: [e.g., "the current user-facing error handling shows a generic UIAlertController with the message 'Something went wrong' for all error types — no distinction between a network timeout (retriable), an authentication failure (requires login), and a data corruption error (requires support contact)"]
- Release deadline and review context: [e.g., "the next major release is in 6 weeks — the release includes a new peer-to-peer transfer feature that adds 3 new async API call paths — the App Store review team has rejected the previous two submissions for crashes reproducible in review"]
- Testing framework: [e.g., "XCTest with no mock networking layer — the current test suite has 38% coverage and zero tests for error path handling — tests run against a live staging API"]
- Monitoring tool: [e.g., "Crashlytics for crash reporting and custom event logging — no structured error logging exists, so the engineering team cannot distinguish between a force-unwrap crash and an async error crash from the crash report alone"]
Deliver:
1. A force-unwrap audit script — a shell script using grep and swiftlint that scans all Swift source files for force-unwrap operators (!) and force-cast operators (as!), outputs a sorted list of occurrences by file with line numbers, and flags the 12 view controllers identified as high-risk — giving the team a prioritized remediation list without a manual file-by-file review
2. A safe optional handling refactoring guide — a before-and-after code pattern for the three most common force-unwrap scenarios in UIKit-based banking apps (cell data source access, storyboard IBOutlet access, and JSON decoding result handling), each showing the force-unwrap version, the safe guard-let or if-let replacement, and the fallback behavior when the optional is nil — with a note on the specific Crashlytics crash type each pattern eliminates
3. A structured error type hierarchy in Swift — a Swift enum-based error hierarchy for the app's three error domains (NetworkError with cases for timeout, unauthorized, serverError, and noConnection; DataError with cases for decodingFailed, corruptedCache, and saveFailed; and AuthError with cases for tokenExpired, invalidCredentials, and sessionRevoked) with associated values for the underlying error and the retry eligibility flag
4. A user-facing error presentation system — a Swift ErrorPresenter class that maps each error type in the hierarchy to a UIAlertController configuration (title, message in plain user language, and primary action — retry, login, or contact support), replacing the current generic 'Something went wrong' alert with an error-specific message that tells the user what happened and what to do next
5. A CoreData thread safety refactoring plan — the Swift concurrency-safe CoreData pattern using NSManagedObjectContext with a private queue context for background saves and a view context for read-only UI access, with the three specific call sites that must be refactored and the XCTest test case that verifies the background save completes without a main thread assertion failure
6. A mock networking layer for error path testing — a URLProtocol subclass that intercepts URLSession requests in XCTest, returns configurable mock responses (success, HTTP 401, HTTP 500, network timeout, and malformed JSON), and enables the error handling code paths to be tested without a live staging API — with eight XCTest test cases covering the async transfer function's behavior for each error type in the NetworkError enum
7. A Crashlytics structured logging implementation — a Swift CrashReporter class that logs a structured Crashlytics custom event for every caught error (error domain, error case, the triggering view controller name, and the retry count if the error is retryable), replacing the current unstructured crash report with a searchable error log that allows the engineering team to distinguish error types and measure the crash-free rate improvement by error category after each fix is deployed
**Write every Swift code pattern as production-ready Swift 5.9 with correct async/await syntax, MainActor annotations where required for UIKit access, and concise inline comments explaining why the safe pattern is used rather than the force-unwrap equivalent — the six junior and mid-level developers who will implement the fixes must understand the safety rationale, not just copy the pattern.**
💡 How to use this prompt
- Run the force-unwrap audit script from output item 1 first and triage the 47 occurrences by view controller risk before writing any new code. The script output will show whether the 34% of crashes from force-unwrapped optionals is concentrated in 2-3 high-risk view controllers or distributed across all 12 — if concentrated, fixing 2-3 files in the first week can eliminate one-third of all crashes before the broader error handling system is in place.
- The most common mistake is replacing all force-unwrap optionals with try? (discarding the error silently) rather than with guard-let or structured error handling. A force-unwrap that is converted to try? stops crashing but starts silently failing — the transaction list that previously crashed on a nil data source will now show an empty list with no error, which is a worse user experience than a crash because the user cannot distinguish between "no transactions" and "failed to load transactions". Every force-unwrap replacement must have an explicit fallback behavior.
- ChatGPT handles this task well and produces correct Swift 5.9 async/await error handling patterns quickly. For the full seven-output system including the CoreData thread safety plan and the Crashlytics structured logging implementation, switch to Claude — it holds the Swift type system and the MainActor annotation requirements consistently across all code patterns without generating UIKit access patterns that violate main thread requirements.
Best Tools for This Prompt
🤖 Best AI Coding Tools for This Prompt
Tested & reviewed — run this prompt with the best AI tools
Related Topics
About This Coding AI Prompt
This free Coding prompt is designed for ChatGPT and works with any modern AI assistant including ChatGPT, Claude, Gemini, and more. Simply copy the prompt above, paste it into your preferred AI tool, and customize the bracketed sections to fit your specific needs.
Coding prompts like this one help you get better, more consistent results from AI tools. Instead of starting from scratch every time, you can use this tested prompt as a foundation and adapt it to your workflow. Browse more Coding prompts →