【问题标题】:How to show exception message in postman?如何在邮递员中显示异常消息?
【发布时间】:2019-09-18 18:36:10
【问题描述】:

我正在使用 REST Web 服务调用从 DB 获取产品列表并检查产品是否为 NULL。

如果没有产品我需要在 POSTMAN 中抛出异常。

谁能介绍一下如何在邮递员中显示异常消息?

代码:

public class ABC extends BusinessException
{
    public ABC(final String message)
    {
        super(message);
    }

    public ABC(final String message, final Throwable cause)
    {
        super(message, cause);
    }
}

【问题讨论】:

  • 将名为 errorMessages 的字符串列表添加到您的响应对象中,捕获您得到的异常,并将它们的消息添加到该列表中
  • @Stultuske 我已经完成了这个..异常打印在控制台上但不在 POSTMAN 中
  • @User2413 你是怎么做到的?显示代码。
  • @User2413 你这样做了,它不会。你能展示你的代码吗?
  • 以下答案可能会有所帮助。 stackoverflow.com/a/599131/6234057

标签: java rest web-services postman


【解决方案1】:

你可以直接使用jax-rs中的WebApplicationException来抛出异常

例如:

if(products==null){
 throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("products does not exist.").build());
}

如果您有自定义异常,则可以扩展 WebApplicationException

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

从您的代码中抛出

 if(products==null){
      throw new BusinessException(Response.Status.NOT_FOUND,"products does not exist.");
 }

你可以使用错误响应对象来显示干净的方式

public class ErrorResponse {
  private int status;
  private String message;
  ErrorResponse(int status,String message){
     this.status = status;
     this.message = message;
  }
//setters and getters here
}

在抛出异常时创建 ErrorResponse 对象

public class BusinessException extends WebApplicationException {
     public BusinessException(Response.Status status, String message) {
         super(Response.status(status)
             .entity(new ErrorResponse(status.getStatusCode(),message)).type(MediaType.APPLICATION_JSON).build());
     }
}

在邮递员中会显示如下

{
  status:404,
  message:"products does not exist."
}

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 2011-09-01
    • 2010-10-02
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 2015-10-05
    相关资源
    最近更新 更多