users@jersey.java.net

Re: [Jersey] Viewable in ExceptionMapper

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Fri, 20 Feb 2009 11:08:00 +0100

On Feb 20, 2009, at 3:07 AM, Charles Brooking wrote:

> G'day,
>
> I've been using the JSP Template Processor for views and have found
> it to
> work well for normal resources, but am unsure if it can be used from
> an
> ExceptionMapper. I'm hoping to serve "custom error pages" using JSP
> templates.
>

It should be possible under certain restrictions. Depending on where
the exception is thrown there may be no matched resources available.

IIUC correctly in your case you are:

   1) using absolute paths to the views, so you do not require the
path to be resolved to the matching resource; and

   2) the model is the exception mapper itself

is that correct?

My guess is that you are using your own ExceptiomMapper to map
WebApplicationException when Jersey is returning a 404 when no
resources are matched.


> If I try this, the view cannot be resolved:
>
> Response
> .fromResponse(exception.getResponse())
> .entity(new Viewable("/WEB-INF/jsp/404.jsp", this))
> .build();
>
> And using the following crashes too (at JSPTemplateProcessor:112),
> because
> uriInfo.getMatchedResources() is empty in the ExceptionMapper.
>
> @Context UriInfo uriInfo;
> @Context TemplateContext templateContext;
> ...
> for (TemplateProcessor t : templateContext.getTemplateProcessors()) {
> String resolvedPath = t.resolve("/WEB-INF/jsp/404.jsp");
> if (resolvedPath != null) {
> return
> Response
> .fromResponse(exception.getResponse())
> .entity(new ResolvedViewable(t, resolvedPath, this))
> .build();
> }
> }
>

This should be possible to fix by checking is there is a matched
resource available or not. In fact it seems useful to extend Viewable
so that a developer can specify a class for which resolving is
performed. By default this would be the matching class if any, but it
might make sense for you for it to be associated with the exception
mapper? that way you can place your views within a certain namespace.

Could you log an issue? and i will work in fixing it.


> Further to this, is there also a means for producing different content
> types (eg HTML, XML, etc) from ExceptionMapper<T>#toResponse()? It
> cannot
> be annotated with @Produces in the usual way.
>

You are correct it cannot be annotated. You need to set the media type
yourself or a default media type will be determined (based on the
Accept header and the Java type you are using).

Paul.