Search code examples
asynchronousswift2alamofire

Swift 2.0: throw exception within an asynchronous piece of code


I am trying to implement the log in service for an application, and I would like to throw an exception if the response status code is not equal to 200. I am using Alamofire as HTTP networking library.

static func loginWithUsername(username: String, andPassword password: String) throws {

    let action = "SmartShoppers/login"
    let url = baseUrl + action


    Alamofire.request(.POST, url, parameters: ["username": username, "password": password])
        .response { request, response, data, error in
            if response?.statusCode != 200 {
                throw ServiceError.LogInError
            }
    }
}

This is the ServiceError enum definition:

enum ServiceError: ErrorType {
    case LogInError
}

What I want to do deal this exception when it is thrown in a function which is called when a button is pressed. This function is in the ViewController class associated with the ViewController that contains that button. The code that is going to be executed is:

do {
    try Service.loginWithUsername(username, andPassword: password)
} catch {
    // SHOW AN ALERT MESSAGE
}

Why am I receiving the message Cannot call value of non-function type 'NSHTTPURLResponse'? Is it the correct way to implement this service? If not please help me.


Solution

  • The closure that you are passing to the response method does not include throws in its signature, so you will not be able to throw an exception from within it.

    IMO this is not a case where you would want to throw an exception, anyways - a non-200 response code is not an exceptional error / failure, and I wouldn't try to use an exception here as a means of control flow.