尝试序列化对象,尽管验证失败

Try to serialize Object although Validation fails

我按照此处所述使用 ResponseObjectSerializable: https://github.com/Alamofire/Alamofire#generic-response-object-serialization

我想验证状态码是否在一个范围内 https://github.com/Alamofire/Alamofire#validation

我的电话是这样的:

Alamofire.request(Router.Something())
        .validate(statusCode: 200..<300)
        .responseObject { (request, response, object:Object?, error) in
            println(object)
            println(request)
            println(response)
}

我的问题是,如果验证失败,无论如何都会调用 responseObject 并尝试序列化空响应。 如果不在我的 ResponseObjectSerializable 中再次验证响应,我该如何处理?

这真是个好问题。

总而言之,您做不到。您的 responseObject 序列化程序未收到有关验证错误的通知。它只接收 requestresponsedata 对象,并且需要尝试从数据构造 object

您发布的 ResponseObjectSerializable link 正是这样做的。如果序列化成功,它将 return 一个有效的对象。如果失败,它将 return 一个 nil 对象和一个序列化错误。

有趣的是,如果您 return 出现序列化错误,但验证也失败了。在这种情况下,您的 completionHandler 实际上将使用 nil 对象和验证错误而不是序列化错误进行调用。如果验证是 responseObject.

之前的 运行,Alamofire 会将验证错误优先于序列化错误

As a sidenote, your responseObject serializer should handle the data coming back from the server safely, regardless of the status code that was returned. If parsing the data fails, your serializer should return a serialization error. If it succeeds, then return the object.