I'm trying to send a sign up request with retrofit and it works perfectly when creating a user is successful. however, when there's an error, it will jump from onResponse
to onFailure
, so I can't handle the error thrown from my server. they both return a Json object
called "message". I tried with postman and it responded correctly but when I'm trying to do it with android, the successful message is shown without any problem but not the error. why is it going to onFailure? I saw several topics where they handled the error on onResponse method but my problem is that the method is not being called when there's an error at all and moved straight to onFailure.
my Activity:
RegisterService registerService = BaseServerRetrofit.getRetrofitInstance().create(RegisterService.class);
RegisterCredential registerCredential = new RegisterCredential(username.getText().toString(),email.getText().toString()
,password.getText().toString(),password.getText().toString());
Call<Message> call = registerService.getMessageFromServer(registerCredential);
call.enqueue(new Callback<Message>() {
@Override
public void onResponse(Call<Message> call, Response<Message> response) {
if(response.code() == 422)
Log.e("400",response.errorBody().toString());
reg_note.setText(response.body().getMessage());
}
@Override
public void onFailure(Call<Message> call, Throwable t) {
reg_note.setText("error");
}
});
RegisterService
public interface RegisterService {
String FEED = "/public/api/auth/signup";
@Headers("Content-Type: application/json")
@POST(FEED)
Call<Message> getMessageFromServer(@Body RegisterCredential registerCredential);
}
I don't know if it necessary to tell you guys, but on success, the response code is 201 and when it fails, it is 422.
edit 1:
I found the exception: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
well, I took a look at the throwable and found out that the header I set was wrong and it was returning a not-Json response. so I changed the header from
@Headers("Content-Type: application/json")
to
@Headers("Accept: application/json")