How to handle empty response in ResponseSerializer

What does it really mean that a response in serializer is empty? How do handle such a situation properly? Right now I'm doing something like this but it's fishy. I realize that I could use a custom error type here, but I think I'm not really supposed to handle this situation with some custom impl - without the serializer there is some specific behavior for this after all?

public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
        
        if let error = error {
            throw error
        }
        
        guard let response = response else {
            throw AFError.responseValidationFailed(reason: AFError.ResponseValidationFailureReason.dataFileNil)
        }
        
        if (200...299).contains(response.statusCode) { ...

}

You can see how Alamofire itself handles it by looking at the built in serializers. For instance, here's DecodableResponseSerializer. In short, empty data is usually considered a failure only if the backend didn't return a 204 or 205 but that behavior is customizable.

I would recommend starting by customizing a DecodableResponseSerializer instance and then move to a fully custom serializer depending on your requirements.

1 Like