when I user the OkHttp Library with a asynchronous way like this:
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
In the onFailure method, how I get the response status code to distinguish different errors. For example, Network error or Server error ?
As far as I remember, onFailure
gets triggered when you get no response. So, if your receive an error, onResponse will be called. You can do something like this in onResponse
:
@Override
public void onResponse(Call call, Response response) throws IOException {
switch(response.code()){
//your desired catched codes here.
}
}
And official doc for onResponse
method:
Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: response may still indicate an unhappy HTTP response code like 404 or 500.
https://github.com/square/okhttp/issues/1769
According to the link, above, onFailure()
is called if and only if there were problems with the client.
If the request was successfully delivered but there was a server problem you can check response.isSuccessful()
. If it returns false, check response.code()
and handle the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With