Catch' block is unreachable but I included try

Viewed 123

I'm getting the following error:

'catch' block is unreachable because no errors are thrown in 'do' block

But my try is present, how can I include the error then?

AF.request(url).responseData(completionHandler: { data in
    do {
        if let apiJsonData = try? JSONDecoder().decode(MyModel.self, from: data.data!){
            self.items = apiJsonData.data.items
        }
    } catch {
        print("Decoding failed -> ERROR:", error)
    }
}

If I include it in the header like: data, error in it throws an error:

Contextual closure type '(AFDataResponse<Data>) -> Void' (aka '(DataResponse<Data, AFError>) -> ()') expects 1 argument, but 2 were used in closure body

How can I have the try catch correctly setup?

1 Answers

You've used try?, not try.

try? turns the whole expression into nil if an error was thrown. It already handles the error on its own, so there's no more error for the catch block to catch. On the other hand, try doesn't do that. For more info, see the Error handling section of the Swift Guide.

If you want the error to be caught by the catch block, you should use try, and delete the if block.

AF.request(url).responseData(completionHandler: { data in
    do {
        let apiJsonData = try JSONDecoder().decode(MyModel.self, from: data.data!)
        self.items = apiJsonData.data.items
    } catch {
        print("Decoding failed -> ERROR:", error)
    }
}

Also note that you are assuming data.data is not nil here. This might not be the case if the network request fails. Better check for it:

AF.request(url).responseData(completionHandler: { data in
    do {
        guard let data = data.data else {
            print("Response Error:", data.error)
            return
        }
        let apiJsonData = try JSONDecoder().decode(MyModel.self, from: data.data!)
        self.items = apiJsonData.data.items
    } catch {
        print("Decoding failed -> ERROR:", error)
    }
}
Related