jakarta-ee - jax-rs Jersey : Exception Mapping for Enum bound FormParam

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

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

 @FormParam("state") final State state

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

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

最佳答案

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

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

关于jakarta-ee - jax-rs Jersey : Exception Mapping for Enum bound FormParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17531920/

相关文章:

java - 带有查询参数的 Jersey DELETE 请求

java - 请求中的 Jersey @matrixparam 和转义分号

java - MobileFirst 7.1 中的 XmlJavaTypeAdapter 不起作用

jakarta-ee - 必须声明元素 web-app

java - 如何使用Contains或matches返回true?

eclipse - tomcat-maven-插件 : Server returned HTTP response code: 403

glassfish - 强制 glassfish 4 使用 Jackson 2.3

java - 从 AJAX 调用异步 Servlet

java - 在 DDD 对象中混合 JSR 303 Bean 验证和手册(通过 Apache Commons)

java - 从现有的 CXF 休息服务生成 wadl