I have client code that communicates with the server to create an account. The communication works, but the error response is not received correctly. In the Objective-C code below, I use AFNetworking
to send the request. I purposely sent an invalid email address and expected the failure
block to get executed, but my code kept going into the success
block.
- (void)createAccount:(NSString *)email
andUsername:(NSString *)username
andPassword:(NSString *)password
success:(SuccessBlock)success
failure:(FailureBlock)failure
{
NSDictionary *params = @{
@"email": email,
@"username" : username,
@"password" : password,
@"client_id" : @"12345"
@"client_secret" : @"abcdef"
};
NSString *requestUrl = [self pathForEndpoint:@"users/new"
withVersion:ServiceRemoteRESTApibbPressExtVersion_1_0];
[self.api POST:requestUrl parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
success(responseObject); // WENT IN THIS PATH
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
failure(error); // EXPECTS THIS PATH
}
];
}
On the server side, my PHP scripts is coded as follow. I did check the debug.log and saw the printed message: *** users_new_REST_API() email invalid
add_action( 'rest_api_init', function () {
register_rest_route( 'bbpress_ext/v1', '/users/new', array(
'methods' => 'POST',
'callback' => 'users_new_REST_API'
) );
} );
public function users_new_REST_API( $request ) {
$user_name = $request['username'];
$password = $request['password'];
$user_email = $request['email'];
$client_id = $request['client_id'];
$client_secret = $request['client_secret'];
if ( ! is_email( $user_email ) ) {
error_log('*** users_new_REST_API() email invalid');
return new WP_Error('email_invalid', 'Invalid email entered.', array( 'status' => 524) );
}
}
I can’t tell if AFNetworking
is misbehaving or the REST-API (beta version 2) for WordPress is broken.
Your understanding of
AFNetworking
error handling is incomplete. The error handler is for networking errors. It doesn’t trigger for HTTP error codes. That’s up to your app to decipher and handle. So, whetherWP_Error
returns a non-2XX HTTP status, or it just returns some kind of JSON object with some error information,AFNetworking
is going to report the request succeeded.It’s not the job of
AFNetworking
to deal with app-level protocol logic.