- 对于此请求:**
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
return
}
}
- 我在控制台中看到以下内容:**
可选(我的应用程序名称.后端错误. jsonSerialization(Alamofire. AFError.响应序列化失败(Alamofire. AFError.响应序列化失败原因. jsonSerializationFailureReason. jsonSerialization失败(错误域= NSCocoaErrorDomain代码= 3840 "字符0周围的值无效。"用户信息= {NSDebugDescription =字符0周围的值无效。})))
- 我所尝试的**
Alamofire.request("https://google.com").responseCollection { (response: DataResponse<[User]>) in
guard response.result.isSuccess else {
print(response.error)
if let error1 = response.error as? AFError {
print(error1) // Execution DOES NOT reach here.
}
if let error2 = response.error as? BackendError {
print(error2) // Execution DOES reach here.
}
return
}
}
print(error2)
以上图纸:
jsonSerialization(Alamofire. AF错误.响应序列化失败(Alamofire. AF错误.响应序列化失败原因. jsonSerialization失败(错误域= NSCocoaErrorDomain代码= 3840 "字符0周围的值无效。"用户信息= {NSDebugDescription =字符0周围的值无效。}))
- 我尝试做的是找到底层错误,以便解析
domain
、code
和userInfo
属性。**
- 我尝试做的是找到底层错误,以便解析
我创建了BackendError
枚举,Alamofire在www.example.com上提供了这个枚举作为示例:https://github.com/Alamofire/Alamofire#handling-errors :
enum BackendError: Error {
case network(error: Error) // Capture any underlying Error from the URLSession API
case dataSerialization(error: Error)
case jsonSerialization(error: Error)
case xmlSerialization(error: Error)
case objectSerialization(reason: String)
}
并且我还实现了与www.example.com上的示例完全相同的示例通用响应对象序列化:https://github.com/Alamofire/Alamofire#generic-response-object-serialization :
extension DataRequest {
@discardableResult
func responseCollection<T: ResponseCollectionSerializable>(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<[T]>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<[T]> { request, response, data, error in
guard error == nil else {
return .failure(BackendError.network(error: error!))
}
let jsonSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonSerializer.serializeResponse(request, response, data, nil)
guard case let .success(jsonObject) = result else {
return .failure(BackendError.jsonSerialization(error: result.error!))
}
guard let response = response else {
let reason = "Response collection could not be serialized due to nil response."
return .failure(BackendError.objectSerialization(reason: reason))
}
return .success(T.collection(from: response, withRepresentation: jsonObject))
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
我认为有switch
es,case
s,以及BackendError
,AFError
,Error
和/或NSError
之间的转换,但我似乎不能得到它。
- 如何找到底层错误,以便解析
domain
、code
和userInfo
属性?**
- 如何找到底层错误,以便解析
我用的是Swift 3和Alamofire 4.3.0。
3条答案
按热度按时间shyt4zoc1#
我知道回答有点晚;- )。但是试试这个:
vnjpjtjt2#
对于Alamofire 4.3,请查看
response.result
:zqry0prt3#
试试这个