How to Catch Specific Error Types in Swift


1 min read

I always forget how to do this and luckily Natalie Panferova at Nilcoalescing wrote a great article about how to provide user friendly descriptions and how to catch specific error types.

I'm mainly writing this so I have access to the part of that article that I forget, which is how to catch a specific error type.

do {
    // Some type of work here
} catch let error as ErrorTypeYouWantToCatch {
    // Do something with that error
} catch {
    // Don't forget to have a catchall incase the error isn't what you expected

Some benefits to catching error types is to present proper user facing notifications or to make the logger calls more useful to you as the developer.

Go read Natalie's article to learn more about customizing error types to make it even easier to present different copy from the error itself.