You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot自定义异常无法在Postman中显示,求排查问题

问题排查:查询ToDo时自定义异常未在Postman显示的原因

核心问题:异常根本没有被抛出

看getSingleToDo方法的逻辑:

public ToDo getSingleToDo(int id){
    ToDo todo=new ToDo(); // 初始化空ToDo对象,todo永远不会为null
    for(ToDo todo1:todos){
        if (todo1.getId() == id) {
            return todo1;
        }
        todo=todo1;
    }
    if(todo==null){ // 此条件永远不成立,todo始终有值
        throw new ResourceNotFoundException("Resource not found exception",HttpStatus.NOT_FOUND);
    }
    return null;
}
  • 代码开头todo=new ToDo()导致变量永远不会为null:即便循环中没找到匹配ID的ToDo,todo最终会被赋值为集合最后一个元素,if(todo==null)判断永远不会触发,自定义异常完全没被抛出,Postman自然看不到异常信息。

其他潜在问题(非当前直接原因,但需修正)

1. 全局异常处理器冗余与缺失

在GlobalExceptionHandler的resourceNotFoundExceptionHandler方法中:

@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ExceptionResponse> resourceNotFoundExceptionHandler(ResourceNotFoundException ex){
    ExceptionResponse response=new ExceptionResponse();
    response.setMessage(ex.getMessage());
    response.setMessage(ex.getMessage()); // 重复调用,属于冗余代码
    response.setSuccess(false);
    // 未设置response的status字段,返回的响应体中status会为null
    return  ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
}
  • 删掉重复的setMessage调用,补充response.setStatus(HttpStatus.NOT_FOUND),确保响应体字段完整。

2. 自定义异常的冗余设计

ResourceNotFoundException中重写getMessage()属于冗余,父类RuntimeException已持有message字段:

public class ResourceNotFoundException extends RuntimeException{
    private HttpStatus status;

    public ResourceNotFoundException(String message, HttpStatus status) {
        super(message);
        this.status = status;
    }

    public ResourceNotFoundException(){
        super();
    }

    // 移除自定义的message字段和重写的getMessage(),直接使用父类实现
    public HttpStatus getStatus() {
        return status;
    }

    public void setStatus(HttpStatus status) {
        this.status = status;
    }
}

3. 响应对象的枚举序列化问题

ExceptionResponse中的status是HttpStatus枚举,默认序列化会输出枚举名称(如"NOT_FOUND")而非数字状态码。如果需要返回数字格式,可将字段改为int类型:

public class ExceptionResponse {
    private String message;
    private boolean success;
    private int statusCode; // 改为int类型存储状态码

    // 构造方法、getter/setter对应修改
    public ExceptionResponse(String message, boolean success, int statusCode) {
        this.message = message;
        this.success = success;
        this.statusCode = statusCode;
    }
}

然后在异常处理器中设置response.setStatusCode(HttpStatus.NOT_FOUND.value())。

修正后的getSingleToDo方法

public ToDo getSingleToDo(int id){
    for(ToDo todo1:todos){
        if (todo1.getId() == id) {
            return todo1;
        }
    }
    // 循环结束未找到匹配项,直接抛出异常
    throw new ResourceNotFoundException("ToDo with id: " + id + " not found", HttpStatus.NOT_FOUND);
}

内容的提问来源于stack exchange,提问作者ssc1234

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:12:58