来自Throwable的错误代码 - Android

Vin*_* TP 0 android error-code throwable

如何从Throwable获取错误代码

public void onFailure(Throwable exception) {

   }
Run Code Online (Sandbox Code Playgroud)

我看到我们可以获取错误消息,LocalizedMessage等

nhp*_*nhp 12

只有HttpException为您提供代码.请务必instance of在使用前进行检查.

这是代码:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)


Fer*_*ano 10

这是 Kotlin 版本:

if(throwable is HttpException){
    when(throwable.code()){
        404->  // Manage 404 error
        else-> // Manage anything else
    }
}
Run Code Online (Sandbox Code Playgroud)


Don*_*pan 0

如果您指的是 500、404 等HTML 错误代码,您可以使用以下代码片段。

if (ex.getCause() != null) // 'ex' is the Exception
    return ex.getCause().getMessage();
Run Code Online (Sandbox Code Playgroud)