0
votes

JAX-RS jersey handle WebApplicationException

Hi,

I'm trying to handle WebApplicationException using MyWebApplicationExceptionMapper, but it is not working.

@Path("/v1")
public class MyHandler {

    @POST
    @Path("/test")
    @Consumes({ MediaType.APPLICATION_JSON})
    @Produces({ MediaType.APPLICATION_JSON})
    public Response getTouchpointPost(@QueryParam("key") KeyParam KeyParam){
    ..
    }
}
 public class KeyParam extends AbstractParam<String> {

    public KeyParam(String param) {
        super(param);
    }

    @Override
    protected String parse(String param) {
        return checkKey(param);
    }

    private String checkKey(String key) {
    // throws IllegalArgumentException if {key expression} is false
        com.google.common.base.Preconditions.checkArgument(isValid(key), "Invalid key %s", key);
        return key;
    }
}

when checkKey() throws IllegalArgumentException, it is caught in catch block and re-thrown as WebApplicationException.

    public abstract class AbstractParam<V> {
        // some code
    public AbstractParam(@JsonProperty("param") String param) {
    // some code

    } catch (Exception e) {
        LOGGER.warn("Exception decoding parameter", e);
        throw new WebApplicationException(onError(param, e));
    }
}


@Provider
public class MyWebApplicationExceptionMapper extends
        BaseExceptionMapper<WebApplicationException> {

    @Override
    public int getStatus(WebApplicationException e) {
        return e.getResponse().getStatus();
    }
}

I have a mapper class which is trying to catch the WebApplicationException. But this mapper class is not able to catch the WebApplicationException exception.

Can someone help me on this? This BaseExceptionMapper is an abstract class which implements ExceptionMapper and generates a custom error message which is returned as a Response object.

I'm not sure what I'm doing wrong here.

This is the stacktrace.

java.lang.IllegalArgumentException: Invalid siteKey ONE
    at com.google.common.base.Preconditions.checkArgument(Preconditions.java:148) 
..
1

1 Answers

3
votes

For those wondering, to have a generic abstract exception mapper:

 public abstract class GenericExceptionMapper  <E extends Throwable>  implements ExceptionMapper<E> {

    protected abstract Response handleResponse(E e);

    @Override
    public Response toResponse(E e) {
        return handleResponse(e);
    }
}

@Provider
public class UserExceptionMapper extends GenericExceptionMapper<UserException>{
    @Override
    protected Response handleResponse(UserException e) {
        return Response.status(Response.Status.BAD_REQUEST).entity(e).build();
    }

}