users@jersey.java.net

[Jersey] Why do IllegalArgumentExceptions cause a 404 instead of a 400?

From: DirkM <dirk_at_olx.com>
Date: Fri, 14 Aug 2009 14:22:23 -0500 (CDT)

I've noticed that an IllegalArgumentException thrown from a resource gets
turned into a WebApplicationException with a 404 HTTP response code.

For example, if I have a service call which takes an int as a parameter, and
I call it as:
http://localhost:8080/myService/path/countryId=notAnInt
it will respond with a 404 (Not Found).

Shouldn't it respond with a 400 (Client Error)?

The workaround I have at the moment is to create a custom exception mapper
like this:

@Provider
@Singleton
public class WebApplicationExceptionMapper implements
ExceptionMapper<WebApplicationException> {
    @Override
    public Response toResponse(WebApplicationException e) {
        int statusCode = e.getResponse().getStatus();

        //
        // IllegalArgumentExceptions are thrown when the client provides an
        // argument to the service that is badly formed, for example
        // countryId=sdfsdf. In that case we want to return an
        // HTTP BAD REQUEST 400. (For some reason 404 is returned by
default)
        //
        if (e.getCause() instanceof IllegalArgumentException) {
            statusCode = Response.Status.BAD_REQUEST.getStatusCode();
        }

        Response.ResponseBuilder builder = Response.status(httpStatusCode);
        // (This is a custom class I wrote for nicer JSON output)
        ThrowableResponse entity = new ThrowableResponse(t,
exceptionStatusCode);
        return
builder.entity(entity).type(MediaType.APPLICATION_JSON).build();
    }
}


Please let me know if there's something I'm missing here.
Thanks,
Dirk
-- 
View this message in context: http://n2.nabble.com/Why-do-IllegalArgumentExceptions-cause-a-404-instead-of-a-400--tp3447019p3447019.html
Sent from the Jersey mailing list archive at Nabble.com.