xcode - 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")
}
解决方案
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
}
推荐阅读
- c# - 泛型和非泛型方法之间的性能差异
- python-3.x - Python beautifulSoup:创建和组合列表并删除像 \n 这样的冗余
- javascript - 延迟框 FadeIn-Animation
- javascript - 三个结构相同的路径之一的 Node.JS 不起作用
- java - 字符串 *list* 的休眠映射(以字符串为键)
- svelte - 如何在 Sapper 中设置基本标签 href 属性?
- mariadb - 使用 DMS 迁移 MariaDB 数据以排除旧记录并减少 RDS 大小
- c# - AutoMapper 版本 9.0.0 - IMappingOperationOptions 上没有 ConfigureMap() 方法
- java - 调用未知类的方法
- mysql - 带有单列表的 MySQL 错误 1064