我试图使用JSONDecoder
来解码从我的服务器使用Alamofire json响应。当我用guard
解码响应时,它没有任何问题。这种方法的副作用是我无法分辨解码实际上失败时的问题。捕获模式更改回调签名
guard let result: TResponseData = try? decoder.decode(TResponseData.self, from: response.data!) else {
self.logger.error("Unable to decode the response data into a model representation.")
return
}
所以不是我想要用do { } catch { }
,但我想不出我应该如何准确的Alamofire responseJSON
回调中使用它。
这就是我目前有:
Alamofire.request(completeUrl, method: .post, parameters: parameters, encoding: encoding, headers: headers)
.validate()
.responseJSON { (response) -> Void in
self.logger.info("POST Response: \(String(describing:response.response?.statusCode))")
switch response.result {
case .success(_):
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom(Date.toTMDBDate)
do {
let _ = try decoder.decode(TResponseData.self, from: response.data!)
} catch DecodingError.dataCorrupted(let error) {
self.logger.error(error.underlyingError)
return
}
completion(result)
return
case .failure(let error):
//....
}
我这个代码给然而什么是对.responseJSON { (response) -> Void in
行编译错误。
将类型为'(_) - > Void'的投掷函数转换为非抛出函数类型'(DataResponse) - > Void'无效转换。
警卫代码工作正常,如果我改变try
到try?
或强制拆开包装,它编译 - 我只是不明白这有我的捕捉处理实际的错误。
如果我更改catch
块,以便它不包含任何模式,则代码将进行编译。
catch {
return
}
这并不能告诉我什么,我的guard
给了我什么。我真的想要捕获decode
操作遇到的错误。我是否使用了错误的模式?为什么使用DecodingError.dataCorrupted
模式似乎会改变回调签名?
真棒谢谢! –
嗨,@哈米什,你为什么不把这个作为答案来写,所以约翰逊可以将它标记为这样! – leanne
@leanne现在就完成了:) – Hamish