Hi guys,
I recently returned to this issue and was able to work around it using an ExceptionMapper to catch the UnrecognizedPropertyException thrown by Jackson and map it to a 400 Bad Request response. Still, it seems to me that this should be handled by Jersey.
@Provider
public class UnrecognizedPropertyExceptionMapper implements ExceptionMapper<UnrecognizedPropertyException>{
@Override
public Response toResponse(UnrecognizedPropertyException exception) {
return Response
.status(Response.Status.BAD_REQUEST)
.entity( "'" + exception.getUnrecognizedPropertyName() + "' is an unrecognized field.")
.type( MediaType.TEXT_PLAIN)
.build();
}
}
________________________________
From: Jeremy Johnson <jeremy.johnson_at_imtc.gatech.edu<mailto:jeremy.johnson_at_imtc.gatech.edu>>
To: "users_at_jersey.java.net<mailto:users_at_jersey.java.net>" <users_at_jersey.java.net<mailto:users_at_jersey.java.net>>
Sent: Tuesday, March 27, 2012 3:00 PM
Subject: [Jersey] Jersey is returning 500 instead of 400 when given an invalid request body
I'm using Jersey's integrated Jackson processing to transform incoming JSON to a POJO argument in the handler method, e.g.:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response newCustomer( CustomerRepresentation customer)
{
...
}
If a client sends JSON with invalid fields Jersey currently returns a 500 Internal Server Error. Instead, I'd like to return a 400 Bad Request. It was indicated to me elsewhere that Jersey *should* return 400 if the parsing fails.
Any insight into what’s going on or how I might convince Jersey to return the a proper 400 error instead of the completely inappropriate 500?
Here's the exception being generated server-side, before my handler is invoked:
javax.servlet.ServletException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException:
Unrecognized field "this_isnt_a_known"_field" (Class com.redacted....
Thanks!
Jeremy