如何在AndroidAnnotations中使用RestErrorHandler?

时间:2014-06-23 17:20:01

标签: android error-handling resttemplate android-annotations

如何正确使用resterrorhandler?我使用AndroidAnnotations 3.0.1 whitch使用springresttemplate for android。

我使用this示例开始,它按预期工作但我应该如何使用它? 我的意思是,如果我使用自定义错误处理程序捕获异常,而不是如何通知活动/片段? 使用自定义错误处理程序,我的方法是:

@Background
public void getAuth() {
    User u = restClient.getAuth(auth); 

//the important part is here
//how do i know here that an error happend except than check user for null? 
//more important how do I pass it the Httperrorcode and a custom headerfield?

    if (u != null) {
        Log.d("XXXX", "Authtoken: " + u.getAuthToken());
    }
    doLater();

    eventManager.fire(Events.Load.dismiss);
}

使用默认的错误处理程序,我的方法是:

@Background
public void getAuth() {
    try {
        User u = restClient.getAuth(auth); //important part here happens a failure
        Log.d("XXXX", "Authtoken: " + u.getAuthToken());
        doLater();
    } catch (RestClientException e) {
        Log.e("XXXX", "error..................");
    }finally{
        eventManager.fire(Events.Load.dismiss);
    }
}

在activity / fragment中处理Httperrorcodes不是很糟糕吗?如果是这样我应该在哪里打电话?

当然,可以从customerrorhandler抛出未经检查的异常,并在异常中传递参数,但我仍然不知道如何访问响应的头字段。

2 个答案:

答案 0 :(得分:1)

可能不是最优雅的解决方案,如果有人有更好的方法,请称重。

  

当然,可以从customerrorhandler抛出未经检查的异常,并在异常中传递参数,但我仍然不知道如何访问响应的头字段。

RestTemplate抛出NestedRuntimeException,特别是HttpClientErrorException,它在发生客户端错误时被包装在NestedRuntimeException中。您可以对HttpClientErrorException进行检查强制转换,以便您访问大部分(如果不是全部)所需的信息。

  

我使用这个例子开始,它按预期工作,但我应该如何使用它?我的意思是,如果我使用自定义错误处理程序捕获异常,而不是如何通知活动/片段?

在自定义错误处理程序中,我抛出一个新的自定义异常(取决于我正在尝试处理的情况),其中包含活动捕获并直接显示的友好消息。例如,如果服务器发送未经授权的401响应,我会抛出一个新的自定义异常,并显示消息“您已经注销,请重新登录以继续”,Activity会相应地显示/处理。

if (runtimeException instanceof HttpClientErrorException) {
       HttpClientErrorException exception = (HttpClientErrorException) runtimeException;

       if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
           throw new DisplayMessageExcpetion("You have logged out, Please log back in to continue");
       } else if (exception.getStatusCode().equals(HttpStatus.BAD_GATEWAY)) {
           etc...
  

//更重要的是如何将Httperrorcode和自定义标题字段传递给它?

如果只需要访问http状态和响应正文,则上述工作正常,如果您需要访问自定义标题字段,则需要提供自己的实现

void handleError(ClientHttpResponse response) throws IOException;
从ResponseErrorHandler

并将其设置为RestTemplate上的错误处理程序。 DefaultResponseErrorHandler的Source应该让您知道如何做到这一点。有关从服务界面获取/设置RestTemplate的信息,请参阅this

答案 1 :(得分:1)

我不确定这是否完全正常(或应该工作),但在我的情况下,如果注入错误处理程序,您调用的方法不会抛出任何异常。但是如果你没有注入错误处理程序,那么对rest服务的调用会引发异常。

这就是我的意思:

    try{
        validate = restClient.validateUser(email, code);

    } catch (Exception e) {
        e.printStackTrace();
    }


@AfterInject
void afterInject() {
    // if the line below is commented, myErrorHandler wouldn't be called to handle errors, and the restClient.method() would throw an exception.
    //restClient.setRestErrorHandler(myErrorHandler);

}