In our REST Services we have used try-catch blocks to catch Exceptions that might occur. But in some cases RuntimeExceptions can be thrown and so far we have no code for handling such exceptions. Our register service, to name one example, could throw a RuntimeException in case the user to be stored in the database is already available (“duplicate key exception”) – I think you would get a javax.transaction.RollbackException to be more precise. Of course, you could simply put userBean.save(user) into a try-catch block and handle any Exception that might occur. Only for demonstration purposes I did not do that. Instead, I have choosen to implement an ExceptionMapper for all of our REST Services. This ExceptionMapper I have named ThrowableExceptionMapper. It is responsible to catch all uncaught Exceptions (more precisely: all uncaught Throwables) that might be thrown. This way we can make sure to always send JSON to the frontend instead of some stack traces (except the case where the user’s session has timed out…), even in case of RuntimeExceptions. The implementation of our ThrowableExceptionMapper class is very simple and looks as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.nabisoft.jaxrs.provider; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import com.nabisoft.json.JsonResponse; @Provider public class ThrowableExceptionMapper implements ExceptionMapper<Throwable>{ private static final Response RESPONSE; private static final JsonResponse JSON = new JsonResponse( "ERROR" ); static { RESPONSE = Response.status( 500 ).entity(JSON).build(); } @Override @Produces (MediaType.APPLICATION_JSON) public Response toResponse(Throwable ex) { System.out.println( "ThrowableExceptionMapper: " +ex.getClass()); ex.printStackTrace(); //usually you don't pass detailed info out (don't do this here in production environments) JSON.setErrorMsg(ex.getMessage()); return RESPONSE; } For more details about this check spring web hosting website.
} |