I am building a REST application, which is running on Glassfish 3, and having trouble handling the case when a parameter is bound to an enum:
@FormParam(\"s
The way that I handled this was to first have a suitable deserializer in my enum:
@JsonCreator
public static Type fromString(final String state)
{
checkNotNull(state, "State is required");
try
{
// You might need to change this depending on your enum instances
return valueOf(state.toUpperCase(Locale.ENGLISH));
}
catch (IllegalArgumentException iae)
{
// N.B. we don't pass the iae as the cause of this exception because
// this happens during invocation, and in that case the enum handler
// will report the root cause exception rather than the one we throw.
throw new MyException("A state supplied is invalid");
}
}
And then write an exception mapper that will allow you to catch this exception and return a suitable response:
@Provider
public class MyExceptionMapper implements ExceptionMapper<MyException>
{
@Override
public Response toResponse(final MyException exception)
{
return Response.status(exception.getResponse().getStatus())
.entity("")
.type(MediaType.APPLICATION_JSON)
.build();
}
}
Hint: It is necessary that MyException extends WebApplicationException. Other exceptions (like an IllegalArgumentException for example) are not handled by any provider in that scope (when parsing the reqest).