简体   繁体   English

获取 Alamofire AFError 错误 Swift 的字符串值

[英]Get string value of Alamofire AFError error Swift

I'm making a request to my server with AlamoFire, and I have a setup something like this, where "self.error" is a String variable.我正在使用 AlamoFire 向我的服务器发出请求,并且我有一个类似这样的设置,其中“self.error”是一个字符串变量。

                    session.request("https://localhost:3000/my-route", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in
                        switch response.result {
                        case .success(let result):
                              print("nice", result)                         
                            
                        case .failure(let err):
                            self.error = err //self.error is a String state variable
                            print("failure")
                        }
                       }

However, I get the (sensible) error "Cannot assign value of type 'AFError' to type 'String'", because I'm trying to set self.error = err , and err is of type AFError, whereas self.error is a String state variable.但是,我收到(明智的)错误“无法将类型 'AFError' 的值分配给类型 'String'”,因为我正在尝试设置self.error = err ,并且err是 AFError 类型,而 self.error 是一个字符串 state 变量。

I realize I could just do something like self.error = "There was an error", but I'd like to provide the user with some feedback as to what the error actually was, and I can't seem to find the correct properties (ie something like err.stringValue, err.description, etc.) to do so.我意识到我可以做一些类似 self.error = "There was an error",但我想向用户提供一些关于错误实际是什么的反馈,我似乎找不到正确的属性(例如 err.stringValue、err.description 等)这样做。 Seems like there's some source code here https://github.com/Alamofire/Alamofire/blob/master/Source/AFError.swift but I'm not sure how this relates to the string value I'd like to obtain.似乎这里有一些源代码https://github.com/Alamofire/Alamofire/blob/master/Source/AFError.swift但我不确定这与我想获得的字符串值有什么关系。

Any help here would be much appreciated.在这里的任何帮助将不胜感激。

You can try err.localizedDescription or you can get the error in the completion of the function and return it completion(error)您可以尝试err.localizedDescription或者您可以在 function 完成时收到错误并返回completion(error)

For such cases you can always use String interpolation eg self.error = "\(err)" , but this is not a good idea because err is not just a string and could contain something like:对于这种情况,您始终可以使用字符串插值,例如self.error = "\(err)" ,但这不是一个好主意,因为 err 不仅仅是一个字符串,并且可能包含以下内容:

sessionTaskFailed(error: Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={_kCFStreamErrorCodeKey=61, NSUnderlyingError=0x280e37750 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <78576E38-D021-4ADC-87D4-1C9D81FF0E3A>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <78576E38-D021-4ADC-87D4-1C9D81FF0E3A>.<1>" ), NSLocalizedDescription=Could not connect to the server., NSErrorFailingURLStringKey=https://localhost:3000/my-route, NSErrorFailingURLKey=https://localhost:3000/my-route, _kCFStreamErrorDomainKey=1})

Like @Menaim already mentioned, you can use err.localizedDescription , then you could get something like URLSessionTask failed with error: Could not connect to the server.就像@Menaim 已经提到的那样,您可以使用err.localizedDescription ,然后您会得到类似URLSessionTask failed with error: Could not connect to the server.

Generally, I would not pass the error directly to the user.通常,我不会将错误直接传递给用户。 This depends at your users, but do they really should know what eg URLSessionTask is?这取决于您的用户,但他们真的应该知道URLSessionTask是什么吗?

In my opinion you should define error string for user, that every user can understand and you should log err.localizedDescription to the console, so you can know what is happening.在我看来,您应该为用户定义错误字符串,每个用户都可以理解,并且您应该将err.localizedDescription到控制台,这样您就可以知道发生了什么。

If your app supports many languages, you can define localizable.strings files and translate the errors.如果您的应用支持多种语言,您可以定义 localizable.strings 文件并翻译错误。

If you do this print("failure") , every time you have an error, how can you distinguish the errors?如果这样做print("failure") ,每次出现错误,如何区分错误?

My suggestion would be something like:我的建议是这样的:

                case .failure(let err):
                    self.error = "There was an error connecting to the server"
                    print("Failed to connect to backend: \(err.localizedDescription)")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift 5 &amp; Alamofire 5:GET 方法错误:Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes) - Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes) “结果”类型的 Alamofire 值<any, aferror> ' 没有成员 'isSuccess' (Swift 5)</any,> - Alamofire Value of type 'Result<Any, AFError>' has no member 'isSuccess' (Swift 5) Alamofire+Combine:如何从 AFError 中获取自定义错误类型 - Alamofire+Combine: how to get custom error type out of AFError 错误:可选(Alamofire.AFError.invalidURL(“”)) - Error: Optional(Alamofire.AFError.invalidURL(“”)) 值:(failure(Alamofire.AFError.explicitlyCancelled)) 使用 Alamofire 发布者时 - value: (failure(Alamofire.AFError.explicitlyCancelled)) when use Alamofire publisher Swift Alamofire将价值放在字符串上 - Swift Alamofire put value to string Alamofire 5:“结果”类型的值<data, aferror> '没有成员'值'</data,> - Alamofire 5: Value of type 'Result<Data, AFError>' has no member 'value' “结果”类型的值 <String> &#39;没有会员&#39;错误&#39;[Alamofire,Swift 5] - Value of type 'Result<String>' has no member 'error' [Alamofire, Swift 5] Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域=NSCocoaErrorDomain 代码=3840 - Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 操作无法完成。 (Alamofire.AFError 错误 9。) - The operation could not complete. (Alamofire.AFError error 9.)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM