I'm using jersey under Glassfish 4.1.
I'm trying to understand the best practice for exception handling. I don't
think that I'm doing right now is correct.
When an exception occurs, I would like to return a json object that
contains an error message.
Let's say I try to add a unit with a duplicate name. The jdbc layer will
throw a duplicate key exception. It appears that this exception is caught
by the container, and not by a try-catch block in the jersey resource.
For example, here is a POST method:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@JsonView(Views.Unit.class)
public Response createUnit(Unit unit) {
try {
// create the unit in the database
return Response.ok(unit).build();
} catch (Throwable e) {
return
Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}