Promisekit: Ability to rethrowing errors in a `.catch` block

Created on 5 Aug 2016  路  2Comments  路  Source: mxcl/PromiseKit

Hey guys! Just started learning Swift with a deep NideJS background and encounter that a closure in a .catch block doesn't marked with throws keyword, so i am unable seamlessly wrap errors on a different application tiers without wrapping all into a new promise instance, its kinda boilertrape

Please take a look at a .catch capabilities in a BluebirdJS promises http://bluebirdjs.com/docs/api/catch.html and maybe we could work on some new features:

  • rethrowing errors
  • recovering from an error state and proceed in the following .then block
  • filtering errors by a given ErrorType as an argument

Providing example from my code:

struct PasswordAuthenticationStrategy: AuthenticationStrategy {
    let email: String
    let password: String
    let api: API = API()

    func issueTokenAsync() -> Promise<Token> {
        return Promise<Token>() {
            resolve, reject in
            api.callEndpointAsync(Endpoint.SignIn(email: email, password: password))
            .then {
                (response: EmptyResponse) -> () in
                let cookieHeader = response.headers["Set-Cookie"]!
                resolve(API.extractAuthCookie(cookieHeader))
            }
            .error {
                err in
                if let apiError = err as? APIError,
                case .ServerError(let code, _) = apiError {
                    switch code {
                    case "invalid_credentials": reject(AuthError.InvalidCredentials)
                    case "trial_expired": reject(AuthError.TrialExpired)
                    case "payment_required": reject(AuthError.TrialExpired)
                    default: reject(AuthError.UnexpectedServerError(apiError: apiError))
                    }
                } else {
                    reject(err)
                }
            }
        }
    }
}

As you can see my Authentication layer encapsulate http error details(such as codes and messages) from a client perspective(which is an UI layer with a login button for example)

Hello @mxcl! what do you think?

Most helpful comment

Use recover. On phone, apologies for brevity.

http://promisekit.org/docs/handbook/Classes/Promise.html#/s:FC10PromiseKit7Promise7recoverFT2onCSo13DispatchQueue6policyOSC11CatchPolicy7executeFzPs13ErrorProtocol_GS0_x__GS0_x_

All 2 comments

Use recover. On phone, apologies for brevity.

http://promisekit.org/docs/handbook/Classes/Promise.html#/s:FC10PromiseKit7Promise7recoverFT2onCSo13DispatchQueue6policyOSC11CatchPolicy7executeFzPs13ErrorProtocol_GS0_x__GS0_x_

Closing as I believe recover does what you want. I have added an FAQ entry for this question.

filtering errors by a given ErrorType as an argument

This feature we do not have, but that would be a welcome addition.

Was this page helpful?
0 / 5 - 0 ratings