简体   繁体   English

Dropwizard资源错误响应

[英]Dropwizard resource error response

In my dropwizard resource, I'm using the built in Jackson JSON object mapping to bind my data. 在我的dropwizard资源中,我正在使用内置的Jackson JSON对象映射来绑定我的数据。

public class WidgetServiceResource {

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

What I noticed however, is when I POST a bad body, the JSON doesn't parse, and I'm served with a response that doesn't meet my company's communication standards. 但是,我注意到的是,当我发布错误的正文时,JSON无法解析,并且收到的响应不符合我公司的通信标准。 How can I customize the response? 如何自定义响应?

You need to deregister all default exception mappers and then register your own to handle the exception you want: 您需要注销所有默认的异常映射器,然后注册自己的映射器以处理所需的异常:

For example, in your yaml, you need: 例如,在您的Yaml中,您需要:

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

Note: registerDefaultExceptionMappers: false will tell DW to not register any ExceptionMappers. 注意: registerDefaultExceptionMappers: false将告诉DW不注册任何ExceptionMappers。

Then, you can implement them yourself. 然后,您可以自己实现它们。 In my case, I will just do a catch-all handler: 就我而言,我将做一个包罗万象的处理程序:

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

}

This reacts to any exception and responds with a 400 and a String. 这对任何异常做出反应,并以400和String响应。

Finally, registering in the main class: 最后,在主类中注册:

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

And a test for proof: 并进行证明测试:

artur@pandaadb:~/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

Hope that helps, 希望能有所帮助,

-- Artur -阿图尔

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

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