【问题标题】:Handling Unauthorised Errors in Retrofit for Asynchronous Calls处理异步调用改造中的未经授权的错误
【发布时间】:2014-07-15 23:51:17
【问题描述】:

我将 Retrofit 用于异步和同步 api 调用。

对于这两者,我定义了一个自定义错误处理程序来处理未经授权的响应。对于同步调用,我在接口方法上声明了自定义异常,我用 try/catch 包围了接口实现,它工作得很好。我可以捕获未经授权的异常。

我对使用回调的异步调用进行了同样的尝试,但效果不一样。我必须在回调的失败方法中处理它,而不是在 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 ....
                }
            }
    );
}

问题是:

是不是应该只处理Callback的failure(RetrofitError)方法中的异常,不要在异步调用的接口方法上声明throws UnauthorisedException

或者最好的实现方式是什么?

【问题讨论】:

    标签: android retrofit


    【解决方案1】:

    答案是肯定的。使用 Retrofit 接口,您无需声明从接口的实现中抛出哪个异常。 RetrofitError 是一个 RuntimeException 因此未选中。预计在 Retrofit 实现失败时会抛出 RetrofitError ,您负责相应地处理它。使用同步方法,您只需使用前面提到的 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);
                    }
                }
        );
    

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

    【讨论】:

    • 谢谢米格尔,完美回答。
    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 2016-01-30
    • 2017-12-23
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多