I have this small snippet that makes a request to a login endpoint and it works fine.
public func loginWithEmail(email: String, password: String, completionHandler: Result<String, NSError> -> Void) {
Alamofire.request(AuthenticationRouter.Login(email: email, password: password))
.validate()
.responseString { response in
completionHandler(response.result)
}
}
My question is: when the user inputs invalid credentials the server returns 403 which due to validate
will generate a Result<NSError>
. What is the best way to modify the error description / failure reason in this error?
Should I create my own error? Is there a way to modify it for all the requests?
Alamofire validate func snippet for reference:
public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { _, response in
if acceptableStatusCode.contains(response.statusCode) {
return .Success
} else {
let failureReason = "Response status code was unacceptable: \(response.statusCode)"
return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
}
}
}
The easiest way would be to act on the error once it reaches your app code. You probably don't want to create a custom validate
method that overrides the default Alamofire behavior because your case is VERY specific.
In general, you would set your acceptable status codes and use the validate(statusCodes:)
method. Then in your response
logic in your app code, switch on the error and create custom app representations of each case. In this case, a 403 means that the incorrect credentials were used which only your application knows. Hence, it should live in your app code, not in an Alamofire validation
extension. My two cents...