Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error code from Throwable - Android

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.

like image 515
Vineesh TP Avatar asked Nov 29 '22 13:11

Vineesh TP


2 Answers

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;
    }
}
like image 114
nhp Avatar answered Dec 04 '22 14:12

nhp


This is the Kotlin version:

if(throwable is HttpException){
    when(throwable.code()){
        404->  // Manage 404 error
        else-> // Manage anything else
    }
}
like image 34
Fernando Prieto Moyano Avatar answered Dec 04 '22 14:12

Fernando Prieto Moyano