我有一个Android应用程序,可以使用Androidannotations和Spring Rest模板消耗RESTful Services。

服务正在正常消费,但是当休眠服务抛出未处理的异常时,即使尝试捕获包括服务消耗,也会停止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;
}
.

我知道异常没有在rentful服务中处理,但我希望我的Android应用程序可以捕获这种类型的问题并向用户展示友好的消息。 但即使尝试捕获:

,也会发生以下错误
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

已经,谢谢!

有帮助吗?

解决方案

在服务器异常的情况下向用户显示友好消息是从泽西岛返回错误状态代码,然后android侧可以处理此响应,并执行操作以向用户显示消息,以显示出错的内容。

所以在您的泽西代码中,您可以添加异常处理:

@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侧,您可以捕获错误实体字符串生成扫描码,然后您可以向用户显示相应的消息,了解发生的内容。例如:

Android侧:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top