2016-10-11 129 views
0

在我的dropwizard资源中,我使用内置的Jackson JSON对象映射来绑定我的数据。Dropwizard资源错误响应

public class WidgetServiceResource { 

    @POST 
    @Path("/widget") 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response foo(ModelParameters c) { 
     return Response.ok(c.value).build(); 
    } 

但是后来我发现,当我发布一个糟糕的机构,JSON不分析,以及我与不符合我公司的通信标准的响应服务。我如何定制响应?

回答

1

您需要注销所有默认的异常映射器,然后注册自己来处理你想要的例外:

例如,在你的YAML,您需要:

server: 
    registerDefaultExceptionMappers: false 
    rootPath: /api/* 
    requestLog: 
    appenders: [] 
    applicationConnectors: 
    - type: http 
    port: 9085 
logging: 
    level: INFO 

注:registerDefaultExceptionMappers: false会告诉DW不注册任何ExceptionMappers。

然后,你可以自己实现它们。就我而言,我将只是做一个包罗万象的处理程序:

public class MyExceptionMapper implements ExceptionMapper<Exception> { 
    @Override 
    public Response toResponse(Exception exception) { 
     return Response.status(400).entity("This makes no sense").build(); 
    } 

} 

这反应任何异常,并有400和串做出响应。

最后,登记在主类:

environment.jersey().register(MyExceptionMapper.class); 

,并证明了一个试验:

[email protected]:~/dev/eclipse/eclipse_jee$ curl -v "http://localhost:9085/api/viewTest" 
* Trying 127.0.0.1... 
* Connected to localhost (127.0.0.1) port 9085 (#0) 
> GET /api/viewTest HTTP/1.1 
> Host: localhost:9085 
> User-Agent: curl/7.47.0 
> Accept: */* 
> 
< HTTP/1.1 400 Bad Request 
< Date: Wed, 12 Oct 2016 10:16:44 GMT 
< Content-Type: text/html 
< Content-Length: 19 
< 
* Connection #0 to host localhost left intact 
This makes no sense 

希望帮助,

- 阿图尔

+0

OMG谢谢。我需要做到这一点,但是我确信我需要在不久的将来实现这样的事情。我回来了 – MedicineMan