I'm not very familiar with error handling and so any advice would be really appreciated.
My code makes multiple calls recursively to the Apple API for calculating a route as it needs to calculate the distance for multiple options.
do {
directions.calculate(completionHandler: {(response, error) in
let response = (response?.routes)! //This line bugs out
for route in response {
//code
completion(result, error)
}
})
}
catch {
print(error.localizedDescription)
}
It tends to crash on the 5th or 6th time, and I wondered if there was a way to stop the application crashing and notify instead.
Thanks
There's no point in using a
do-catchblock, since there's nothrowablefunction in your code, so you won't be able to catch any errors. In Swift you can only catch errors thrown by a function markedthrows, all other errors are unrecoverable.You should safely unwrap the optional
response, since it might benil, in which case the force unwrapping would cause an unrecoverable runtime error that you have already been experiencing.You can use a
guardstatement and optional binding to safely unwrap the optionalresponseand exit early in case there's noresponse.