【问题标题】:jax-rs jersey: Exception Mapping for Enum bound FormParamjax-rs jersey:枚举绑定 FormParam 的异常映射
【发布时间】:2013-07-08 16:47:20
【问题描述】:

我正在构建一个在 Glassfish 3 上运行的 REST 应用程序,并且在处理参数绑定到枚举时遇到问题:

 @FormParam("state") final State state

所以,State 只是一个枚举,它包含不同类型的状态。

如果提交了无法解析的值,则返回 http 400。这个基本没问题。但是,我需要拦截该异常并返回自定义响应,该响应为客户端提供额外信息。 (例如,包含描述的 json 对象:“状态无效”)。我已经将参数绑定到我自己的类,并且能够正确处理异常,但是我找不到任何关于在使用枚举时如何处理这种情况的信息。我想我也可以为此使用专门的类,但如果可以保留枚举,我想避免这种情况。

【问题讨论】:

    标签: jakarta-ee jersey jax-rs glassfish-3


    【解决方案1】:

    我处理这个问题的方法是首先在我的枚举中有一个合适的反序列化器:

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

    【讨论】:

    • 谢谢。我不知道枚举也是通过 fromString() 解析的。文档对此有点模糊。实际上我从未尝试过,因为它看起来有点奇怪。
    【解决方案2】:

    提示:MyException 必须扩展 WebApplicationException。其他异常(例如 IllegalArgumentException)不会由该范围内的任何提供者处理(在解析请求时)。

    【讨论】:

      猜你喜欢
      • 2011-03-18
      • 1970-01-01
      • 2015-10-07
      • 2013-02-17
      • 2012-08-28
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多