Could not get the server error message from Alamofire 3.3.0

為{幸葍}努か 提交于 2019-11-30 14:38:20

I managed to get it to work exactly the way I want is by dropping the status validation and check for the statusCode manually

Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                if response.response?.statusCode == 200 {
                    print("Success with JSON: \(response.result.value)")

                    success(updatedUser)
                }
                else {
                    let error = response.result.value as! NSDictionary
                    let errorMessage = error.objectForKey("message") as! String
                    print(errorMessage)
                    failure(errorMessage)
                }


        }

This is how to get the error domain, code and user info with Alamofire 4 and Swift 3. User info contains the error strings.

Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
            .validate(statusCode: 200..<300)
            .validate(contentType: ["application/json"])
            .responseJSON { response in
                switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")
                    success(updatedUser)
                case .Failure(let error):
                    let errorCode = error._code
                    let errorDomain = error._domain
                    let userInfo = error._userInfo
                    print("Request failed with error: \(error), code: \(errorCode), domain: \(errorDomain)")
                    failure(error)
                }

        }

updated for swift 3 :

Used below lines of code:-

    Alamofire.request(escapedString!, method: .get, encoding: JSONEncoding.default)
        .validate(contentType: ["application/json"])
        .responseJSON { response in
            if response.response?.statusCode == 200 {
                print("Success with JSON: \(String(describing: response.result.value))")

            }
            else {
                let error = (response.result.value  as? [[String : AnyObject]])
                print(error as Any)
            }
    } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!