问题描述
我想要实现的是我有一个 NetworkManager
来处理服务器的 request
,并通过 AFError
处理错误。
但是,有时当服务器响应为 4xx 时,会出现带有该响应的自定义消息,我想将其显示给用户,但不知道如何实现。
这是我的NetworkManager
static let shared:NetworkManager = {
return NetworkManager()
}()
typealias completionHandler = ((Result<Data,AFError>) ->Void)
func handleAFrequest(request: DataRequest,completion: @escaping completionHandler) {
request.validate(statusCode: 200..<300)
request.responseJSON { (response) in
switch response.result {
case .success(_):
if let data = response.data {
completion(.success(data))
}
case .failure(let error):
print(error.localizedDescription)
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
completion(.failure(.invalidURL(url: URL)))
case .responseValidationFailed(let reason):
print("Response validation Failed: \(error.localizedDescription); Reason:\(reason)")
completion(.failure(.responseValidationFailed(reason: reason)))
除了错误之外,我还希望能够投射服务器响应,并向用户显示响应的 Message
。
StatusCode 为 4xx 时的服务器响应示例:
{
"data":
"code":401;
"Message":"Phone Invalid"
}
解决方法
我已经在我的许多项目中解析了 api 错误。我相信有更好的选择来处理用户的显示或错误(如果有的话)。请查看我的代码,如果有错误,我会在吐司中显示它。在 Toast 中显示不是重点,但您可以看到我如何处理代码中的错误情况,并且它从未失败过。请根据您的 api 调用相应地更改参数
func postMethod(mylist: [String:Any]) {
print(K.APIUrl)
print(K.port)
AF.request("\(K.urlFromUrlField!):\(K.configPort)/snhttp-01?",method: .put,parameters: mylist)
.authenticate(username: username,password: password)
.response { response in
switch response.result {
case .success:
print("\nValidation Successful from put method")
print(response.result)
print(response.value as Any)
//get xml code and error msg if any
if let response = response.data{
let xml = XML.parse(response)
print(xml)
print("\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")" )
let code = xml.Response.Code.text ?? "No code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
}
else{
print("\nSuccess block: Request Successfully sent,BUT there was nothing from the server to unwrap! / nothing sent back from the server\nThis is the data sent to the server: \(mylist["data"] ?? "No data in data key of the parameter")")
}
case let .failure(error):
if let response = response.data {
let xml = XML.parse(response)
let code = xml.Response.Code.text ?? "\nNo code value in response"
let responseMessage = xml.Response.Message.text ?? "No message returned from server"
print("\nCode value from server: \(code)")
print("\nResponse message from server: \(responseMessage)")
print(error)
}
else {
print("\nFailure Block: A connection to the server could not be established")
}
}}
}
此代码解析来自 api 的 xml。但是,您可以放弃它,只关注我如何处理响应以及由此产生的错误。