Besi
Besi

Reputation: 22939

Error handler not called for promise

I have a service, which fails when I enter bad login credentials. However, my Promise error handler does not get called.

I don't seem to grasp what's wrong with my code so that the error callback is never reached.

Service

func loadRepositories() -> Promise<[Repository]>{
    return Promise { fullfill, reject in
        manager.request(Method.GET, baseURL + "/api/1.0/user/repositories")
            .authenticate(user: username, password: password)
            .responseArray { (response: Response<[Repository], NSError>) in
                switch response.result{
                case .Success(let value):
                    fullfill(value)
                case .Failure(let e):
                    // The breakpoint here is reached.
                    reject(e)
                }
        }
    }
}

Handling

firstly{
    service!.loadRepositories()
}.then { repositories -> Void in
    loginVC.dismissViewControllerAnimated(true, completion: nil)
    self.onLoginSuccessful()
}.always{
    // Always gets called 
    loginVC.isSigningIn = false
}.error { error in
    // I never get here even though `reject(e)` is called from the service.
    loginVC.errorString = "Login went wrong"
}

Upvotes: 1

Views: 1187

Answers (1)

VolenD
VolenD

Reputation: 3692

By default error does not handle cancellation errors and bad credentials is exactly a cancellation error. If you put print(e.cancelled) before reject(e), you will see that it will return true. If you give a wrong URL for example, you will receive false. In order to get around this, just replace

}.error { error in

with:

}.error(policy: .AllErrors) { error in

and error will be triggered then. In case you use recover, cancellation errors will be handled by default. You can check https://github.com/mxcl/PromiseKit/blob/master/Sources/Promise.swift#L367 for more information.

Upvotes: 5

Related Questions