如果远程服务返回401
,我将尝试添加对响应状态代码的检查。
我正在尝试使用PromiseKit URLSession
扩展名。
想象我有一些基本的东西,例如
return firstly {
URLSession.shared.dataTask(.promise, with: request)
}.compactMap {
try JSONDecoder().decode(T.self, from: $0.data)
}
我想做的是添加对响应状态代码的检查,因此我可能会抛出错误并执行一些其他步骤。
类似
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
}
有例外
无法将类型'PMKFinalizer'的返回表达式转换为返回类型'承诺'
是否可以引入retryWhen
之类的内容,使我能够发现错误并检查?
由于.catch
不返回任何内容,但您想返回Promise<T>
,因此必须在此处删除.catch
,
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
将由被调用者实现。
或者,也许你看起来像,
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)
})
}