我正在对异步和同步api调用使用改型。
对于这两种情况,我都定义了一个自定义错误处理程序来处理未经授权的响应。对于在接口方法上声明了自定义异常的同步调用,我用try/catch包围接口实现,它工作得很好。我可以捕捉未经授权的异常。
我也尝试过使用回调的异步调用,但它的工作方式不同。我必须在回调的failure方法中处理异常,而不是在try/catch中捕捉异常。
以下是接口方法:

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

以下是实现方法:
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 ....
                }
            }
    );
}

问题是:
我应该只处理回调的failure(reformationerror error)方法中的异常,而不声明在异步调用的接口方法上引发未授权的异常吗?
或者什么是实现这一点的最佳方法?

最佳答案

答案是肯定的。使用改型接口时,不会声明从接口上的实现引发哪个异常。改装错误是一个运行时异常,因此未选中。预计改造实施失败时会抛出一个改造错误,您负责相应地处理它。使用同步方法,您只需使用前面提到的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);
                }
            }
    );

希望这能为你澄清一些事情!

关于android - 处理异步调用翻新中的未授权错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24760450/

10-11 22:43
查看更多