Alamofire返回.Success错误HTTP状态代码 [英] Alamofire returns .Success on error HTTP status codes

查看:475
本文介绍了Alamofire返回.Success错误HTTP状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的场景,我正在努力。我正在使用Alamofire在rest API上注册用户。第一次注册调用成功,用户可以登录。第二次调用,当尝试使用相同的电子邮件地址注册时,应该从服务器获得HTTP状态代码409。但是,Alamofire会返回一个带有空请求和响应的.Success。我用postman测试了这个API,它正确地返回了409.

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 log in. The second call, when trying to register with the same email address should result in a HTTP status code 409 from the server. Alamofire, however, returns a .Success with an empty request and response. I have tested this this API with postman and it correctly returns a 409.

为什么Alamofire没有返回.Failure(错误),错误有状态代码信息等?

Why is Alamofire not returning .Failure(error), where the error has status code info etc?

这是我每次使用相同输入运行的调用。

Here is the call I run with the same input each time.

Alamofire.request(.POST, "http://localhost:8883/api/0.1/parent", parameters: registrationModel.getParentCandidateDictionary(), encoding: .JSON).response(completionHandler: { (req, res, d, e) -> Void in
        print(req, res, d, e)
    })


推荐答案

来自Alamofire 手册

From the Alamofire manual:


验证

Validation

默认情况下,无论响应的内容如何,​​Alamofire都会将完成的任何请求视为成功,
。如果响应具有
不可接受的状态代码或MIME类型,则在
响应处理程序之前调用validate会导致生成错误。

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

您可以再次使用手册中的验证方法手动验证状态代码:

You can manually validate the status code using the validate method, again, from the manual:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
     .validate(statusCode: 200..<300)
     .validate(contentType: ["application/json"])
     .response { response in
         print(response)
     }

或者您可以使用验证 c>半自动验证状态代码和内容类型没有参数:

Or you can semi-automatically validate the status code and content-type using the validate with no arguments:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
     .validate()
     .responseJSON { response in
         switch response.result {
         case .success:
             print("Validation Successful")
         case .failure(let error):
             print(error)
         }
     }

这篇关于Alamofire返回.Success错误HTTP状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆