使用最新的Jersey(2.22.1),我已经成功创建了我的自定义验证器以满足各种需求。但是,当发生ConstraintViolationException时,我的自定义ExceptionMapper
(在web.xml中注册为provider
)不会被调用,尽管它被定义为ExceptionMapper<Throwable>
。
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="mywebapp" version="2.5">
<display-name>Some Name - Webapp</display-name>
[...]
<servlet>
<servlet-name>jersey_v2-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
com.myfirm.web.rest.providers.DefaultExceptionMapper,
com.myfirm.web.rest.endpoints.XxxEndpoint,
com.myfirm.web.rest.endpoints.XxyEndpoint,
com.myfirm.web.rest.endpoints.XyzEndpoint
</param-value>
</init-param>
<init-param>
<param-name>jersey.config.beanValidation.enableOutputValidationErrorEntity.server</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey_v2-servlet</servlet-name>
<url-pattern>/rest/1.0/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>jersey_v2-servlet</servlet-name>
<url-pattern>/rest/latest/*</url-pattern>
</servlet-mapping>
[...]
</web-app>
DefaultExceptionMapper
@Provider
public class DefaultExceptionMapper implements ExceptionMapper<Throwable> {
private static final Logger LOG = LoggerFactory.getLogger(DefaultExceptionMapper.class);
@Override
public Response toResponse(Throwable caughtException) {
LOG.warn("Exception caught in the REST layer", caughtException);
Throwable original = caughtException;
// some business logic to convert the exception to a response
// log & return the response
Response response = status(status).entity(entity).build();
return response;
}
@XmlRootElement
public static class Error {
@XmlElement
public String type;
@XmlElement
public String message;
@XmlElement
public String translationKey;
}
}
使用我的调试器,我可以在类org.glassfish.jersey.server.ServerRuntime第596行看到已解析的映射器不是我的,但是org.glassfish.jersey.server.validation.internal.ValidationExceptionMapper
。
如果DefaultExceptionMapper
,我如何告诉泽西岛使用我的ConstraintViolationException
?
PS:我已尝试过此处建议的选项:ExceptionMapper not invoked if receiving invalid JSon没有运气。
答案 0 :(得分:3)
将映射器定义为implements ExceptionMapper<ConstraintViolationException>
使得它以某种方式优先于为同一异常类型注册的其他映射器。
我最终得到了2个异常映射器,一个用于每个异常,另一个用于ConstraintViolationException
,两者都扩展了相同的抽象类。
答案 1 :(得分:0)
现在,通过完全禁用泽西岛的bean验证,这是一个简单的解决方法。这可以通过让Application子类返回一个将ServerProperties.BV_FEATURE_DISABLE设置为true的属性来完成。
例如:
@ApplicationPath("")
public class MyApplication extends Application {
@Override
public Map<String, Object> getProperties() {
return Collections.singletonMap(ServerProperties.BV_FEATURE_DISABLE, true);
}
}