translating exceptions

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

translating exceptions

This post has NOT been accepted by the mailing list yet.
All of my ServerResource subclasses have methods containing exception translation boilerplate, like this:

public class MyResource extends MyBaseResource {
    public Foo getFoo() {
        Foo result = null;
        try {
            result = ....
        catch (RuntimeException e) {
        return result;

and then MyBaseResource implements doCatch like this:

    protected void doCatch(final RuntimeException e) {
        Class<?> exceptionClass = e.getClass();
        if (IllegalArgumentException.class.isAssignableFrom(exceptionClass)) {
            // chain & translate to a 400
            throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e.getMessage(), e);
        if (UnsupportedOperationException.class.isAssignableFrom(exceptionClass)) {
            // chain & translate to a 405
            throw new ResourceException(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, e.getMessage(), e);
        /* etc.... I have some other custom exception classes that I map to other HTTP statuses. */

        throw e;

It would be nice if I didn't have to put that try/catch boilerplate in all my @Get, @Put, @Post, etc. methods.

I was thinking that a method like
    protected ResourceException translateException(final RuntimeException e)

defined on ServerResource would be nice to have.  It could be called from ServerResource.doHandle if an exception is thrown, giving the resource object a chance to do the translation to a ResourceException.  If that method returned null, then ServerResource could do its own translation.