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("state") final State state
So, State is just an enum, which contains different types of states.
In case a value is submitted, that can not be parsed, a http 400 is returned. This basically is fine. However, I need to intercept that exception and return a custom response, which provides additional information to the client. (e.g. a json object containing a description: "state invalid"). I have bound parameters to my own classes and have been able to address the exception handling properly, but I couldn't find any information on how to handle this case when using an enum. I guess I can use a dedicated class for that as well, but I would like to avoid that, if it is possible to keep the enum.
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();
}
}