我处理这个问题的方法是首先在我的枚举中有一个合适的反序列化器:
@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");
}
}
然后编写一个异常映射器,它可以让你捕获这个异常并返回一个合适的响应:
@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();
}
}