Propagate Swift Errors Using Throwing Functions
Written by Team Kodeco
If you call a function that throws an error in Swift, you can either handle the error directly with the do-catch
statement or you can propogate the error by making functions as throwing.
This allows the caller of the function to handle the error, rather than the function itself.
Here is an example of using a throwing function:
enum SimpleError: Error {
case somethingWentWrong
}
func doSomething() throws -> String {
if true {
throw SimpleError.somethingWentWrong
}
return "Success!"
}
func performAction() throws -> String {
return try doSomething()
}
do {
let result = try performAction()
print(result)
} catch {
print("Error: \(error)")
}
In this example, the performAction()
calls doSomething()
, which can throw an error. However, rather than handling the error within performAction()
, the function marks itself with throws
to indicate that it’ll propogate the error without handling it.
It’s important to note that if a function is marked as throwing, all of its callers must also be marked as throwing or be called within a do-catch statement to handle the error.
It’s good practice to document the possible errors that a throwing function can throw, so that the caller knows how to handle them.