jax-rs jersey: Exception Mapping for Enum bound FormParam

南笙酒味 提交于 2019-12-01 23:25:01

问题


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.


回答1:


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();
  }
}



回答2:


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



来源:https://stackoverflow.com/questions/17531920/jax-rs-jersey-exception-mapping-for-enum-bound-formparam

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