我有一个Android应用程序,它使用AndroidAnnotations和Spring Rest Template使用RESTful服务。

服务已被正确使用,但是当RESTful服务引发未处理的异常时,即使尝试捕获包含服务使用,Android应用程序也会停止运行并关闭。

android-app:

@RestService
protected StudentRESTfulClient mStudentRESTfulClient;

@Click(R.id.register_button)
public void register(Student user) {
    try {
        this.mStudentRESTfulClient.insert(user);
    } catch (Exception exception) {
        // This block is not executed...
    }
}


restful-app:

@POST
public Student insert(Student entity) {
    this.getService().insert(entity); // Throw the exception here!
    return entity;
}


我知道RESTful服务未处理该异常,但是我希望我的Android应用程序可以捕获此类问题并向用户显示友好消息。
但是即使使用try catch,也会发生以下错误:

01-11 00:44:59.046: E/AndroidRuntime(5291): FATAL EXCEPTION: pool-1-thread-2
01-11 00:44:59.046: E/AndroidRuntime(5291): org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
01-11 00:44:59.046: E/AndroidRuntime(5291): at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:78)
01-11 00:44:59.046: E/AndroidRuntime(5291): at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:524)


如果他们想查看整个项目,请使用Git存储库:https://github.com/veniltonjr/msplearning

已经,谢谢!

最佳答案

在服务器发生异常的情况下向用户显示友好消息的方法是从Jersey返回错误状态代码,然后Android端可以处理此响应,并采取措施向用户显示错误消息。

因此,在您的Jersey代码中,您可以添加异常处理:

@POST
public Response insert(Student entity) {
    Response r;
    try {
        this.getService().insert(entity); // Throw the exception here!
        r = Response.ok().entity(entity).build();
    } catch (Exception ex) {
        r = Response.status(401).entity("Got some errors due to ...!").build();
    }
    return r;
}


在Android方面,您可以捕获错误实体字符串"Got some errors due to ...!",然后可以向用户显示有关所发生情况的适当消息。例如:

Android方面:

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
String responseText = EntityUtils.toString(response.getEntity());


这将确保在REST异常的情况下,Android客户端可以处理该错误并向用户显示一条消息。

08-04 06:15
查看更多