jax-rs jersey: Exception Mapping for Enum bound FormParam

偶尔善良 提交于 2019-12-01 20:21:26

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!