java - 如何在 postman 中显示异常消息?

标签 java rest web-services postman

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

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

任何人都可以阐明如何在 postman 中显示异常消息吗?

代码:

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

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

最佳答案

你可以直接使用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());
     }
}

在 postman 中它将显示如下

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

关于java - 如何在 postman 中显示异常消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55915169/

相关文章:

带有基本身份验证的 iOS swift Web 服务调用

java - 用户搜索功能使用 Java 驱动程序查询 MongoDB 中的数据

java - 使用 java Swing 中的 Jframe 调整 Jpanel 的大小

java - 使Java设置线程安全

java - 使用 jersey-spring3 和现有的 Spring 应用程序上下文来休息 web 服务

java - Jersey - 在运行时设置 REST 响应编码

rest - 如何使用REST API从Nexus中使用分类器删除 Artifact ?

java - 通过查询参数选择 Jersey 方法

java - 以复杂数据类型作为输入的 Web 服务

java - 文件读取 : Getting partial Output