Jakarta ee jax-rs-jersey:枚举绑定FormParam的异常映射
我正在构建一个在Glassfish 3上运行的REST应用程序,在处理参数绑定到枚举时遇到问题:Jakarta ee jax-rs-jersey:枚举绑定FormParam的异常映射,jakarta-ee,jersey,jax-rs,glassfish-3,Jakarta Ee,Jersey,Jax Rs,Glassfish 3,我正在构建一个在Glassfish 3上运行的REST应用程序,在处理参数绑定到枚举时遇到问题: @FormParam("state") final State state 因此,状态只是一个枚举,它包含不同类型的状态 如果提交了无法解析的值,则返回http 400。这基本上是好的。但是,我需要截获该异常并返回一个自定义响应,该响应向客户端提供附加信息。(例如,包含描述的json对象:“状态无效”)。我已经将参数绑定到自己的类,并且能够正确地处理异常处理,但是我找不到有关如何在使用枚举时处理
@FormParam("state") final State state
因此,状态只是一个枚举,它包含不同类型的状态
如果提交了无法解析的值,则返回http 400。这基本上是好的。但是,我需要截获该异常并返回一个自定义响应,该响应向客户端提供附加信息。(例如,包含描述的json对象:“状态无效”)。我已经将参数绑定到自己的类,并且能够正确地处理异常处理,但是我找不到有关如何在使用枚举时处理这种情况的任何信息。我想我也可以为此使用专用类,但如果可以保留枚举,我希望避免使用专用类。我处理此问题的方法是首先在枚举中使用合适的反序列化器:
@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();
}
}
@Provider
公共类MyExceptionMapper实现ExceptionMapper
{
@凌驾
公众响应(最终MyException异常)
{
返回Response.status(exception.getResponse().getStatus())
.实体(“”)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
提示:MyException必须扩展WebApplicationException。其他异常(例如IllegalArgumentException)不由该范围内的任何提供者处理(在解析请求时)。谢谢。我不知道枚举也是通过fromString()解析的。文件在这方面有点含糊不清。实际上我从来没有试过,因为它看起来有点奇怪。