处理异步调用的改进中的未经授权的错误

El *_*ano 2 android retrofit

我正在使用Retrofit进行异步和同步api调用.

对于两者,我都定义了一个自定义错误处理程序来处理未经授 对于同步调用,我已经在接口方法上声明了自定义异常,我用try/catch包围了接口实现,它完美无缺.我可以捕获未经授权的例外情况.

我已尝试使用回调的异步调用,但它不起作用.而不是在try/catch中捕获Exception,我必须在回调的失败方法中处理它.

这是接口方法:

@GET("getGardenGnomes")
void getGardenGnomes(@Header("Authorisation") String authorisation, Callback<GardenGnomes> callback) throws UnauthorisedException;
Run Code Online (Sandbox Code Playgroud)

这是实施:

void onClick() {
    try {
        getGardenGnomes()
    } catch (UnauthorisedException exception) {
        // .... handle the exception ....
    }
}

void getGardenGnomes() throws UnauthorisedException {
    // .... get client etc etc ....

    client.getGardenGnomes(authorisation, new Callback<GardenGnomes>() {
                @Override
                public void success(GardenGnomes gardenGnomes, Response response) {
                    // .... do something ....
                }

                @Override
                public void failure(RetrofitError error) {
                    // .... handle error ....
                }
            }
    );
}
Run Code Online (Sandbox Code Playgroud)

问题是:

我应该只处理Callback的失败(RetrofitError错误)方法中的异常,并且不要在异步调用的接口方法上声明抛出UnauthorisedException吗?

或者实现这个的最佳方法是什么?

Mig*_*gne 11

anwser是的.使用Retrofit接口,您不会声明从接口上的实现抛出哪个异常.因此,RetrofitError是未选中的RuntimeException.预计Retrofit将在Retrofit实现失败时抛出,并且您负责相应地处理它.使用同步方法,您只需使用您提到的try/catch.使用异步方法,您可以在故障回调方法中处理它.

public void methodToHandleRetrofitError(RetrofitError error) {
    // handle the error
}

// Synchronous
try {
    client.getGardenGnomes(authorization)
} catch (RetrofitError e) {
    methodToHandleRetrofitError(e);
}

// Asynchronous
client.getGardenGnomes(authorisation, new Callback<GardenGnomes>() {
                @Override
                public void success(GardenGnomes gardenGnomes, Response response) {
                    // .... do something ....
                }

                @Override
                public void failure(RetrofitError error) {
                    methodToHandleRetrofitError(error);
                }
            }
    );
Run Code Online (Sandbox Code Playgroud)

希望这能为你澄清事情!