swifturlsessionpromisekit

PromiseKit w/ URLSession


I am trying to add a check against the response status code in the event my remote service returns a 401.

I have am trying to use the PromiseKit URLSession extension.

Imagine I have something basic such as

        return firstly {
            URLSession.shared.dataTask(.promise, with: request)
        }.compactMap {
            try JSONDecoder().decode(T.self, from: $0.data)
        }

What I would like to do is add a check against the response state code, so I may throw an error and execute some further steps.

Something like

        return firstly {
            URLSession.shared.dataTask(.promise, with: request)
        }.map { session  in
            if (session.response as? HTTPURLResponse)?.statusCode == 401 {
                // throw a custom error here
                // something like
                // throw TokenProviderError.unauthorized
            }

            return session.data

        }.compactMap {
            try JSONDecoder().decode(T.self, from: $0)
        }.catch { error in
            // check the error thrown here and do something
        }

This has an exception

Cannot convert return expression of type 'PMKFinalizer' to return type 'Promise'

Is it possible to introduce something like retryWhen which will allow me to catch an errors and check?


Solution

  • As .catch doesn't return anything but you want to return a Promise<T> so you have to remove .catch here as,

    return firstly {
        URLSession.shared.dataTask(.promise, with: request)
    }.map { session  in
        if (session.response as? HTTPURLResponse)?.statusCode == 401 {
            // throw a custom error here
            // something like
            // throw TokenProviderError.unauthorized
        }
    
        return session.data
    
    }.compactMap {
        try JSONDecoder().decode(T.self, from: $0)
    }
    

    .catch will be implemented by the callee.


    OR, may be you are looking something like,

    func test() -> Promise<Any> {
        return firstly(execute: { () -> Promise<String> in
            return .value("bhai")
        }).map({ string -> Promise<Double?> in
            return .value(0.1)
        }).compactMap({ double -> NSError in
            return NSError(domain: "", code: 0, userInfo: nil)
        })
    }