users@jsr311.java.net

Re: Telling ExceptionMapper to exclude exceptions

From: cowwoc <cowwoc_at_bbs.darktech.org>
Date: Mon, 13 Oct 2008 11:54:48 -0400

>
> cowwoc wrote:
>> Hi Marc,
>>
>> I'd like to process all uncaught RuntimeExceptions thrown by
>> resource methods. I'm simply trying to ensure that resource methods
>> returns a valid response even if the code forgets to catch an exception.
> In my application, I'm actually taking the opposite approach -- my
> resource method throws an exception for an "exceptional condition"
> :-), and I then rely on an exception mapper to do the right thing.
> For example, let's say I want to return a 404 Not Found when the
> client presents an id that is not found.
>
> @Path("/customers")
> public class CustomersResource {
> ...
> @GET
> @Path("{id}")
> public Response find(@PathParam("id") String id) {
> Customer customer = MyBusinessLogic.findCustomer(id);
> if (customer != null) {
> return Response.ok(customer).build();
> } else {
> throw new NotFoundException();
> }
> }
> }
>
> And I have an exception mapper for NotFoundException that emits a
> 404. This has seemed pretty elegant so far. In particular, it avoids
> the need for the developer creating resource classes from having to
> remember "now which HTTP status do I use for this particular use case"
> and sometimes getting it wrong.
>
> I supply exception mappers for all the exceptional conditions that I
> care about at the application level (AuthenticationException -> 401,
> AuthorizationException -> 403, and so on). If there's no such mapper,
> you end up with a 500, which seems like the correct behavior.
>
> Craig
>

    Craig, that's not the opposite approach. I'm advocating the exact
same thing. The point is that the underlying code might throw some
exception which you didn't plan for and you want to ensure that it gets
translated into some useful Response. You'd need to catch *both*
NotFoundException as well as any other unexpected RuntimeException.

Gili