Check out Mapping Exceptions to Responses in the Jersey docs:
https://jersey.java.net/documentation/latest/user-guide.html#d0e5206
Maybe you can create an ExceptionMapper for the JDBC exception?
Hope this helps!
- Paul
On Wed, Oct 29, 2014 at 9:45 AM, Rick Schumeyer <rschumeyer_at_gmail.com>
wrote:
> (sorry first message got sent before I finished typing it)
>
> 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.
> Glassfish returns an html page.
>
> 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) {
> // this never gets called
> return
> Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
> }
> }
>
> What is the correct way to handle exceptions that occur while processing a
> jersey resource under glassfish?
>