首页 > 解决方案 > How to get reason from custom error enum on Swift failure Result

问题描述

In order to track server errors from a Restfull Api on an SwiftUI IOS App I am feeding the error message from NSData to the "reason" parameter of next NetworkErrors enum:

enum NetworkError: Error {
    case domainError(reason:String)
    case decodingError(reason:String)
    case encodingError(reason:String)
}

The error reason is fed when decoding the NSURLSession response:

static func postRequest<T:Decodable, U:Codable>(_ endpoint:String, _ input:U?, completion: @escaping (Result<T,NetworkError>) -> Void) {
        ...
                 do {
                     let retval = try JSONDecoder().decode(T.self, from: data)
                     completion(.success(retval))

                     } catch let DecodingError.dataCorrupted(context) {
                        let responseData = String(data: data, encoding: String.Encoding.utf8)
                        completion(.failure(.decodingError(reason: responseData ?? "Data corrupted from response")))
                     } catch {
                         ...
                     }
    ...
}

The error reason should be available on next code, but I'm only able to print the localizedDescription:

Button(action:{
    self.postRequest(endpoint, self.value){ (result: Result<Bool,NetworkError>) in
        switch result {
                        case .success:
                            print("value saved successfully")
                        case .failure(let error):
                            print("failure to save value")
                            print(error.localizedDescription)                            
                        }
        }
    }){
        Image(systemName:"icloud.and.arrow.up")
    }

标签: xcodeswiftui

解决方案


In the failure case, we know that error is a NetworkError, so now disassemble that error with another switch:

switch error {
case .domainError(let reason): // do something
case .decodingError(let reason): // do something
case .encodingError(let reason): // do something
}

推荐阅读