简体   繁体   English

Dropwizard 异常映射

[英]Dropwizard Exception Mapping

I have created two ExceptionMappers:我创建了两个 ExceptionMappers:

GenericExceptionMapper implements ExceptionMapper<Throwable>

and

ValidationExceptionMapper implements ExceptionMapper<javax.validation.ValidationException>

The GenericExceptionMapper checks if the Exception is of a specific type and if it is some mapping will be done. GenericExceptionMapper 检查异常是否属于特定类型,如果是特定类型,则将进行某种映射。 In all other cases it will be mapped to a 500.在所有其他情况下,它将映射到 500。

The ValdiationExceptionMapper will map to a 400 with a specific response. ValdationExceptionMapper 将映射到具有特定响应的 400。

Now i'm observing several strange things.现在我正在观察一些奇怪的事情。 If i omit the ValidationExceptionMapper the GenericExceptionMapper is not called.如果我省略 ValidationExceptionMapper,则不会调用 GenericExceptionMapper。 Furthermore if i cut of the database connection non of the ExceptionMappers will be triggered.此外,如果我切断了 ExceptionMappers 的数据库连接非将被触发。 In both cases the response is a 500 html format.在这两种情况下,响应都是 500 html 格式。 What i actually want is that every exception should be catched by the mapper.我真正想要的是每个异常都应该被映射器捕获。

I'm using Dropwizard 1.0.5 with the setting registerDefaultExceptionMappers: false .我正在使用 Dropwizard 1.0.5 和设置registerDefaultExceptionMappers: false

First of all, I don't think setting @Singleton is good idea for a Resource.首先,我不认为设置@Singleton 是一个资源的好主意。

On the other hand: This is the correct way to customize the response given for a particular exception by implementing ExtendedExceptionMapper :另一方面:这是通过实现ExtendedExceptionMapper自定义为特定异常给出响应的正确方法:

environment.jersey().register(new ExtendedExceptionMapper<WebApplicationException>() {
@Override
public Response toResponse(WebApplicationException exception) {
    return Response.status(Response.Status.NOT_FOUND).build();
}

@Override
public boolean isMappable(WebApplicationException e) {
    return Throwables.getRootCause(e).getClass() == MustacheNotFoundException.class;
}});

Dropwizard docs, Templates errors section Dropwizard 文档,模板错误部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM