【问题标题】:jersey 2.0 jaxrs RI - return json string on exceptionjersey 2.0 jaxrs RI - 在异常时返回 json 字符串
【发布时间】:2013-07-18 19:59:41
【问题描述】:

我正在使用 jersey 2.0 创建一个 REST 服务。我正在扩展 WebApplicationException

引发特定异常的方法

if(json.equals("") || json.equals(" ")) {
      throw new ArgumentException("bad post data");
}


      public class ArgumentException extends RestException  {
         .....

         public ArgumentException(String message) {
             super(Status.BAD_REQUEST,message);
         }
    }


    public class RestException extends WebApplicationException  {
    ...........
     public RestException(Status status, String message) {

             super(Response.status(status)
                     .entity(message)
                     .type("text/plain")
                     .build()); 
             /*
             super(Response.status(status)
                     .entity(new ErrorBean(status.getStatusCode(),message))
                     .type(MediaType.APPLICATION_JSON)
                     .build()); */

         }


ErrorBean is a POJO

在 RestException 中以纯字符串形式返回错误的方法有效(正确的 http 代码 400 和消息)。但是,当我尝试传递 ErrorBean POJO 并使用 MediaType.APPLICATION_JSON 作为响应时,我收到一条错误消息,提示“标头已发送”,http 错误代码为 500(因此管道存在一些内部问题)和空响应。

我也看过这个问题Returning JSON or XML for Exceptions in Jersey

我怎样才能将异常代码和消息作为 JSON 格式返回

{"code" : 400, "message" : .... }

更新

我收到了关于 SO 以及球衣用户邮件列表的答复。步骤是

  • 非 AJXB POJO 不需要任何注释
  • 在您的应用程序中注册 JacksonFeature

ResourceConfig rc = new ResourceConfig().packages("test").register(JacksonFeature.class);

【问题讨论】:

    标签: rest jersey jax-rs jersey-2.0


    【解决方案1】:

    你需要在你的Application/ResourceConfig中注册JacksonFeature,即:

    // Create JAX-RS application.
    final Application application = new ResourceConfig()
            .packages("org.glassfish.jersey.examples.jackson")
            .register(JacksonFeature.class)
            // No need to register this provider if no special configuration is required.
            .register(MyObjectMapperProvider.class);
    

    查看documentation 以获取在泽西岛的杰克逊支持以及example

    【讨论】:

    • 谢谢。这就是缺少的。为了他人的利益,我添加了一个完整的示例。
    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 2011-02-21
    • 2017-11-14
    • 2011-07-20
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    相关资源
    最近更新 更多