Search code examples
swifterror-handlingcrashmkdirection

How to handler an error of MKDirectionsRequest


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


Solution

  • There's no point in using a do-catch block, since there's no throwable function in your code, so you won't be able to catch any errors. In Swift you can only catch errors thrown by a function marked throws, all other errors are unrecoverable.

    You should safely unwrap the optional response, since it might be nil, in which case the force unwrapping would cause an unrecoverable runtime error that you have already been experiencing.

    You can use a guard statement and optional binding to safely unwrap the optional response and exit early in case there's no response.

    directions.calculate(completionHandler: {(response, error) in
        guard let response = response, error == nil else {
            completion(nil,error)
            return
        }
    
         for route in response.routes {
             ....
             completion(result, nil)
         }
    })