How can I get the error code from the Throwable?
public void onFailure(Throwable exception) {
}
I saw that we can get the error messages, LocalizedMessage
, etc.
How can I get the error code from the Throwable?
public void onFailure(Throwable exception) {
}
I saw that we can get the error messages, LocalizedMessage
, etc.
Only HttpException gives you the HTTP error code. Make sure you check instance of
before using it.
Here is the code:
if (throwable instanceof HttpException) {
HttpException exception = (HttpException) throwable;
switch (exception.code()) {
case 400:
// Handle code 400
break;
case 500:
// Handle code 500
break;
default:
break;
}
}
This is the Kotlin version:
if(throwable is HttpException){
when(throwable.code()){
404-> // Manage 404 error
else-> // Manage anything else
}
}
If you meant HTML error codes like 500, 404, etc., you can use the following code snippet.
if (ex.getCause() != null) // 'ex' is the Exception
return ex.getCause().getMessage();
Use:
public void onFailure(Throwable exception) {
Log.i("onFailure", "Throwable ", exception);
}
You try this.
Similar to nhp's answer, but I didn't get the (exception.code()) option using the HttpException class, so I used the HttpResponseException class instead.
if (throwable instanceof HttpResponseException) {
HttpResponseException exception = (HttpResponseException) throwable;
eturn exception.getStatusCode());
}
If you use the retrofit2-rxjava2 adapter by Jake Wharton,
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
Then use:
if(throwable is com.jakewharton.retrofit2.adapter.rxjava2.HttpException){ val code = throwable.code }
© 2022 - 2024 — McMap. All rights reserved.