Skip to Content
Course content

115: Recovering from Errors Gracefully

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time: a developer writes a do-catch block, throws a print(error) inside the catch, and thinks they've "handled" the error. On the developer's machine, it looks fine because the error pops up in the Xcode console. But for the user? The app just stops responding, a loading spinner spins forever, or a button simply does nothing when clicked.

struct ProfileManager {
    func loadUserProfile() async {
        do {
            let profile = try await NetworkService.shared.fetchProfile()
            self.userProfile = profile
        } catch {
            // The classic mistake: logging is not handling.
            print("Error loading profile: \(error)")
        }
    }
}

The "Silent Fail" Trap

The code above is technically "safe" in that it won't crash the app, but it's a failure in user experience. If the network is down or the server returns a 404, the catch block executes, prints a message that the user will never see, and the function exits. The app is now in a "zombie state"—the UI thinks it's still loading, but the logic has already given up.

Recovering gracefully means moving from detecting an error to responding to it in a way that keeps the user in control. You need to bridge the gap between the Swift error and the UI state.

Mapping Errors to User Actions

To fix this, we need to stop treating all errors as the same. A "no internet" error requires a different recovery path than a "password expired" error. I prefer using pattern matching in the catch block to determine exactly how the app should recover.

enum ProfileError: Error {
    case noInternet
    case serverDown
    case userNotFound
}

struct ProfileManager {
    var errorMessage: String?
    var shouldShowRetryButton = false

    func loadUserProfile() async {
        do {
            self.userProfile = try await NetworkService.shared.fetchProfile()
            self.errorMessage = nil
            self.shouldShowRetryButton = false
        } catch ProfileError.noInternet {
            self.errorMessage = "You're offline. Please check your connection."
            self.shouldShowRetryButton = true
        } catch ProfileError.serverDown {
            self.errorMessage = "Our servers are taking a nap. Try again in a few minutes."
            self.shouldShowRetryButton = true
        } catch {
            self.errorMessage = "Something went wrong. We're not quite sure what."
            self.shouldShowRetryButton = false
        }
    }
}

Now, the app actually recovers. Instead of a frozen screen, the user gets a clear explanation and a way to fix the problem. I've also added a generic catch at the end—always do this. You can't predict every possible error (like a system-level memory issue), so you need a safety net to ensure the UI doesn't just hang.

Strategic Retries and Fallbacks

Sometimes, the most graceful recovery is one the user doesn't even notice. If you're loading a profile picture and it fails, does the whole screen need to show an error? Probably not. A better approach is a fallback.

I often implement a "silent retry" for transient errors. If the first attempt fails due to a timeout, try once more before bothering the user. If that also fails, fall back to a cached version of the data or a placeholder image. This creates a seamless experience where the app feels resilient rather than fragile.




📋 Practical Task

Building a Robust File Importer with Retry Logic

You are building a feature that imports a JSON configuration file from a local directory. Currently, the code just fails and prints to the console if the file is missing or corrupted.

Your Task: Refactor the FileImporter class to implement graceful recovery. You must:

  • Define a FileError enum with cases for fileNotFound and corruptedData.
  • Modify the importConfig() method to use do-catch with specific pattern matching.
  • If fileNotFound occurs, the app should call a method createDefaultConfig() to generate a fresh file and then attempt to import it again.
  • If corruptedData occurs, the app should set a userAlertMessage variable informing the user that the file is broken and they must manually delete it.
  • Ensure there is a final catch-all block to handle unexpected system errors.
// Starting point
class FileImporter {
    var userAlertMessage: String?
    
    func importConfig() {
        do {
            try performImport()
        } catch {
            print("Import failed: \(error)")
        }
    }
    
    func performImport() throws {
        // Imagine this throws FileError.fileNotFound or .corruptedData
    }
    
    func createDefaultConfig() {
        print("Creating a fresh default config file...")
    }
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.