Understanding AFNetworking - Error
Contents
When using AFNetworking, I want to get the status code in case of failure
NSError in failure block
1 |
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager]; |
The error.code
is not the HTTP status code, it is NSError
that AFNetworking creates due to serializer error
How AFNetworking creates NSError
AFURLSessionManager.m
In URLSession:task:didCompleteWithError:
1 |
NSError *serializationError = nil; |
AFErrorWithUnderlyingError
This is called in validateResponse:data:error:
and responseObjectForResponse:data:error
of AFURLResponseSerialization
classes
1 |
static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { |
Error Domain
In AFURLResponseSerialization.h
Error codes forAFURLResponseSerializationErrorDomain
correspond to codes inNSURLErrorDomain
.
For example
1 |
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); |
HTTP Status code
Inspect userInfo of NSError
The NSError userInfo contains AFNetworkingOperationFailingURLResponseErrorKey
and AFNetworkingOperationFailingURLResponseDataErrorKey
that we can inspect to get NSURLResponse and NSData
Replace NSError
Sometimes we don’t care about NSURLErrorDomain
, we can get HTTP Status Code from NSURResponse and replace the code in the NSError
1 |
NSURLSessionDataTask *task = [self.manager dataTaskWithRequest:request |