【问题标题】:How to include a message in a BadRequestException?如何在 BadRequestException 中包含消息?
【发布时间】:2016-11-01 10:42:30
【问题描述】:

是否可以在BadRequestException 中包含一条消息,以便当用户看到响应代码 400 时,他/她也可以找出原因?

场景大概是这样的,经过简化:

public Entity getEntityWithOptions(@PathParam("id") String id, @QueryParam("option") String optValue) {
    if (optValue != null) {
        // Option is an enum
        try {
            Option option = Option.valueOf(optValue);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException(e.getMessage());
        }
        return new Entity(option);
    }
    return new Entity();
}

我知道这可以通过返回 Response 对象来完成,但我不希望这样。

这可能吗?也许是ExceptionMapper<BadRequestException>?或者因为BadRequestException 已经是泽西岛特有的例外,所以无法做到这一点?

【问题讨论】:

  • 我认为消息可以放入构造函数中,对吧?并且如果使用了exceptionMapper,它实际上会返回一个Response。
  • 我正在将消息传递给构造函数,但响应中不包含它。
  • 如果使用了 exceptionMapper,则显示传递给构造函数的消息。只需像这样制作映射器: public Response toResponse(BadRequestException e) { return Response.status(Response.Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN).entity(ExceptionUtils.getStackTrace(e)).build();}

标签: java web-services http jersey jax-rs


【解决方案1】:

您可以使用BadRequestException(Response response)constructor 来完成。

例如:

String msg = e.getMessage();
throw new BadRequestException(Response.status(BAD_REQUEST)
                .entity(msg).build());

【讨论】:

    【解决方案2】:

    有一个非常简单的方法,如下所示。

    Response.ResponseBuilder resp_builder=Response.status(Response.Status.BAD_REQUEST);
    resp_builder.entity(e.getMessage());//message you need as the body
    throw new WebApplicationException(resp_builder.build());
    

    如果您需要添加标头、响应媒体类型或其他一些功能,ResponseBuilder 提供所有这些。

    【讨论】:

      【解决方案3】:

      您可以抛出 CustomException 并将其映射到 CustomExceptionMapper 以提供自定义响应。

      public class CustomException extends RuntimeException {    
          public CustomException(Throwable throwable) {
              super(throwable);
          }
      
          public CustomException(String string, Throwable throwable) {
              super(string, throwable);
          }
      
          public CustomException(String string) {
              super(string);
          }
      
          public CustomException() {
              super();
          }
      }
      
      @Provider
      public class CustomExceptionMapper implements ExceptionMapper<CustomException> {
          private static Logger logger = Logger.getLogger(CustomExceptionMapper.class.getName());
          /**
           * This constructor is invoked when exception is thrown, after
           * resource-method has been invoked. Using @provider.
           */
          public CustomExceptionMapper() {
              super();
          }
      
          /**
           * When exception is thrown by the jersey container.This method is invoked  
           */
          public Response toResponse(CustomException ex) {
              logger.log(Level.SEVERE, ex.getMessage(), ex);
              Response.ResponseBuilder resp = Response.status(Response.Status.BAD_REQUEST)
                              .entity(ex.getMessage());
      
              return resp.build();
          }
      }
      

      像这样在代码中使用 CustomException。

      public Entity getEntityWithOptions(@PathParam("id") String id, 
                                         @QueryParam("option") String optValue) 
                                         throws CustomException {
          if (optValue != null) {
              // Option is an enum
              try {
                  Option option = Option.valueOf(optValue);
              } catch (IllegalArgumentException e) {
                  throw new CustomException(e.getMessage(),e);
              }
              return new Entity(option);
          }
          return new Entity();
      }
      

      除了message之外,你还可以构造一个对象并通过CustomException将它传递给mapper。

      【讨论】:

        【解决方案4】:

        你应该像这样创建一个自定义异常

        public class CustomBadReq extends WebApplicationException {
             public CustomBadReq(String message) {
                 super(Response.status(Response.Status.BAD_REQUEST)
                     .entity(message).type(MediaType.TEXT_PLAIN).build());
             }
        }
        

        另见this

        【讨论】:

          猜你喜欢
          • 2014-12-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-19
          相关资源
          最近更新 更多