0

JSONDecoderAlamofire を使用して、サーバーからの 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パターンを使用するとコールバック シグネチャが変わるように見えるのはなぜですか?

4

1 に答える 1