Question

I have an Android application that consumes RESTful services using AndroidAnnotations and Spring Rest Template.

The services are being consumed properly, but when the RESTful service throws an unhandled exception the Android application stops running and is closed, even with the try catch encompassing service consumption.

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;
}

I know that the exception is not being treated in RESTful service, but I want my Android application can catch this type of problem and display a friendly message to the user. But the following error occurs even with the 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 repository if they want to look at the whole project: https://github.com/veniltonjr/msplearning

Already, thanks!

Was it helpful?

Solution

The way to show the user a friendly message in case of server exception is to return a error status code from Jersey and then the Android side can handle this response and do the action to display a message to user that something goes wrong.

So in your Jersey code, you can add exception handling:

@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;
}

On Android side, you can catch the error entity string "Got some errors due to ...!" and then you can display appropriate message to the user about what happened. For example:

Android side:

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

This will ensure that in case of REST exception, Android client can handle the error and display a message to user.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top