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
}
したがって、代わりに a を使用したいのですdo { } catch { }
が、 AlamofireresponseJSON
コールバック内でどのように使用する必要があるのか わかりません。
これは私が現在持っているものです:
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' への無効な変換。
ガード コードは正常に動作し、a に変更try
するtry?
かアンラップを強制すると、コンパイルされます。実際のエラーを catch で処理することはできません。
catch
パターンを含まないようにブロックを変更すると、コードはコンパイルされます。
catch {
return
}
これは、私が私に与えていたもの以上に何もguard
与えません。操作で発生したエラーをキャプチャしたいのですdecode
。間違ったパターンを使用していますか? DecodingError.dataCorrupted
パターンを使用するとコールバック シグネチャが変わるように見えるのはなぜですか?