NEW: Learn to build the incredible iOS 15 Weather app today! >>

SOLVED: Please Help: Error in success/failure block "'catch' block is unreachable because no errors are thrown in 'do' block"

Forums > Swift

I am writing a closure with error handling, but I am getting a warning "'catch' block is unreachable because no errors are thrown in 'do' block" in the catch line. This is my code:

class Service {
func graphQL(body: [String:Any], onSuccess: @escaping (Foundation.Data) -> (), onFailure: @escaping (Error) -> ()) {
    var request = URLRequest(url: url)

    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)

    URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            onFailure(error)
        }

        if let data = data {
            do{
                onSuccess(data)
            }
            catch{
                onFailure(error)
            }
        }
    }.resume()
}

class TimeDepositManager {
func getTimeDeposits(onSuccess: @escaping ([TimeDeposits]) -> (), onFailure: @escaping (Error) -> ()) {
    let body = ["query": "{ account { timeDeposits { returnAmount interestRate dueDate originalAmount id startDate currency } } }"
    ]

    Service().graphQL(body: body, onSuccess: { data in
        let json = try? JSONDecoder().decode(GraphQLResponse.self, from: data)
        onSuccess(json?.data?.account?.timeDeposits ?? [])
    }, onFailure: { error in
        print(error)
    })
}

I want the logic of onSuccess in the func getTimeDeposits(), but how remove this catch block warning?

   

The point is that your onSuccess function isn't marked as throws and doesn't throw any errors. That's what the compiler tells you. If it were you would need to call it with try and that's why the catch block is unreachable.

if let data = data {
  onSuccess(data)
}

You handled the error case before.

   

It looks like you're confused with error handling techniques.

Take a quick peek at the documentation for dataTask(with:)

Apple Documentation: dataTask(with:)

// funtion's signature
func dataTask(with request: URLRequest,  completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void)

This function's signature tells you that dataTask takes two parameters: the URLRequest object, and a function that you provide. Remember! Functions are first class objects in Swift. You can create them and pass them around as variables.

The function you provide must accept three parameters: a Data object, a URLResponse object, and an Error object. Actually, they are all optionals, so you may get nils instead of actual objects.

What does your function return? Void! nada. zilch. Nut-N-Honey.

Notice the function's signature doesn't say it throws! This means if it detects an error, the function won't abrubtly stop and burp out an error message you have to catch and interpret. Instead, this function is designed to return an Error object. Instead of catching an error, you need to take a look at the error parameter and see if anything's inside the box.

// Here's an example of a function signature that throws
init(contentsOfFile path: String) throws

Because dataTask(with:) doesn't throw errors, there is nothing for your method to catch, as @hatsushira points out. Since there is nothing to catch, the compiler warns you that your onFailure(error) code will never be executed.

Paul has a nice article on do / try / catch. Do / Catch

In your code, this section essentially checks for errors from your URLRequest:

if let error = error {  // Sure enough!  error has something in it. It's NOT nil!
     onFailure(error) // open the error box and take a look inside.
     // Probably should exit here.
}

This section then verifies you received data:

if let data = data {  // Yup! There's something in the data package left at the front door.
     onSuccess(data)  // Open it up and see what's inside.
}      

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED Learn the most up-to-date techniques and strategies for testing new and legacy Swift code in this free practical course for iOS devs who want to become complete Senior iOS Developers.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.