Get the error code from Throwable - Android
Asked Answered
B

6

8

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.

Beckford answered 28/6, 2017 at 8:41 Comment(2)
What error code? Throwable has no such fieldElenor
Please check the answer belowLexicography
L
26

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;
    }
}
Lexicography answered 28/6, 2017 at 11:25 Comment(0)
M
10

This is the Kotlin version:

if(throwable is HttpException){
    when(throwable.code()){
        404->  // Manage 404 error
        else-> // Manage anything else
    }
}
Miamiami answered 11/12, 2019 at 15:47 Comment(0)
L
0

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();
Liven answered 28/6, 2017 at 8:46 Comment(0)
G
0

Use:

public void onFailure(Throwable exception) {
    Log.i("onFailure", "Throwable ", exception);
}

You try this.

Garnettgarnette answered 28/6, 2017 at 8:54 Comment(0)
M
0

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());
}
Machos answered 20/5, 2019 at 11:41 Comment(0)
H
0

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 }
Herrmann answered 12/12, 2020 at 9:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.