倾销不良要求 [英] Dumping bad requests
问题描述
我有一个用Dropwizard实现的服务,我需要将不正确的请求转储到某个地方.
I have a service implemented with Dropwizard and I need to dump incorrect requests somewhere.
我看到有一个可能性可以自定义通过注册ExceptionMapper<JerseyViolationException>
来显示错误消息.但是我需要完整的请求(标题,正文),而不仅是ConstraintViolations
.
I saw that there is a possibility to customise the error message by registering ExceptionMapper<JerseyViolationException>
. But I need to have the complete request (headers, body) and not only ConstraintViolations
.
推荐答案
You can inject ContainerRequest
into the ExceptionMapper
. You need to inject it as a javax.inject.Provider
though, so that you can lazily retrieve it. Otherwise you will run into scoping problems.
@Provider
public class Mapper implements ExceptionMapper<ConstraintViolationException> {
@Inject
private javax.inject.Provider<ContainerRequest> requestProvider;
@Override
public Response toResponse(ConstraintViolationException ex) {
ContainerRequest request = requestProvider.get();
}
}
在ContainerRequest
中,您可以使用getHeaderString()
或getHeaders()
获得标头.如果要获取主体,则需要做一些改动,因为在到达映射器时,Jersey已经读取了实体流.因此,我们需要实现ContainerRequestFilter
来缓冲实体.
In the ContainerRequest
, you can get headers with getHeaderString()
or getHeaders()
. If you want to get the body, you need to do a little hack because the entity stream is already read by Jersey by the time the mapper is reached. So we need to implement a ContainerRequestFilter
to buffer the entity.
public class EntityBufferingFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
ContainerRequest request = (ContainerRequest) containerRequestContext;
request.bufferEntity();
}
}
您可能不希望针对所有请求调用此过滤器(出于性能原因),因此您可能希望使用名称绑定).
You might not want this filter to be called for all requests (for performance reasons), so you might want to use a DynamicFeature
to register the filter just on methods that use bean validation (or use Name Binding).
一旦注册了此过滤器,就可以使用ContainerRequest#readEntity(Class)
读取正文.您可以像在客户端使用Response#readEntity()
一样使用此方法.因此,对于该类,如果要保持其通用性,可以使用String.class
或InputStream.class
并将InputStream
转换为字符串.
Once you have this filter registered, you can read the body using ContainerRequest#readEntity(Class)
. You use this method just like you would on the client side with Response#readEntity()
. So for the class, if you want to keep it generic, you can use String.class
or InputStream.class
and convert the InputStream
to a String.
ContainerRequest request = requestProvider.get();
String body = request.readEntity(String.class);
这篇关于倾销不良要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!