Error code from Throwable - Android

谁都会走 提交于 2019-12-08 14:07:15

问题


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


回答1:


Only HttpException gives you 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;
        }
    }



回答2:


If you meant error code like 500 , 404 etc , you can use the following code snippet.

if (ex.getCause() != null) // ex is the Exception
            return ex.getCause().getMessage();



回答3:


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

you try this




回答4:


Similar to nhp answer but i didn't get the ( exception.code() ) option using HttpException class so i used HttpResponseException class instead.

  if (throwable instanceof HttpResponseException) {
            HttpResponseException exception = (HttpResponseException) throwable;
            return exception.getStatusCode());
    }


来源:https://stackoverflow.com/questions/44797634/error-code-from-throwable-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!