Alamofire returns .Success on error HTTP status codes

后端 未结 4 1112
北海茫月
北海茫月 2020-12-29 03:16

I have a pretty simple scenario that I\'m struggling with. I\'m using Alamofire to register a user on a rest API. The first call to register is successful and the user can l

4条回答
  •  星月不相逢
    2020-12-29 03:33

    Here is my code for AlamoFire error catching:

    switch response.result {
                    case .success(let value):
                        completion(.success(value))
                    case .failure(var error):
    
                        var errorString: String?
    
                        if let data = response.data {
                            if let json = try? (JSONSerialization.jsonObject(with: data, options: []) as! [String: String]) {
                                errorString = json["error"]
    
                            }
                        }
                        let error = MyError(str: errorString!)
                        let x = error as Error
                        print(x.localizedDescription)
                        completion(.failure(x))
    
                    }
    

    and the MyError class difinition:

    class MyError: NSObject, LocalizedError {
            var desc = ""
            init(str: String) {
                desc = str
            }
            override var description: String {
                get {
                    return "MyError: \(desc)"
                }
            }
            //You need to implement `errorDescription`, not `localizedDescription`.
            var errorDescription: String? {
                get {
                    return self.description
                }
            }
        }
    

提交回复
热议问题