jax-rs jersey: Exception Mapping for Enum bound FormParam

后端 未结 2 493
挽巷
挽巷 2021-01-20 06:37

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         


        
相关标签:
2条回答
  • 2021-01-20 06:59

    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();
      }
    }
    
    0 讨论(0)
  • 2021-01-20 07:03

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

    0 讨论(0)
提交回复
热议问题