springboot 配置全局异常 处理

一、依赖(基于springmvc)

<!--spring-web-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

二、创建全局异常类

package com.wt.lease.common.exception;

import com.wt.lease.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @ExceptionHandler(Exception.class)
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail();
    }
}

 三、主动使用全局异常结合返回结果码

1、自定义RuntimeException的子类

package com.wt.lease.common.exception;

import com.wt.lease.common.result.ResultCodeEnum;
import lombok.Data;

/**
 * @Description: TODO
 * @Author: 1872428
 * @Date: 2025/5/13 11:00
 * @Version: 1.0
 **/
@Data
public class LeaseException extends RuntimeException{
    private Integer code;
    private String message;

    public LeaseException(ResultCodeEnum resultCodeEnum){
        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
    }
}

2、在全局异常配置类中,添加上面异常类的处理方法

package com.wt.lease.common.exception;

import com.wt.lease.common.result.Result;
import com.wt.lease.common.result.ResultCodeEnum;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail();
    }

    @ExceptionHandler(LeaseException.class)
    public Result error(LeaseException e){
        return Result.fail(e.getCode(), e.getMessage());
    }

}

3、新增返回结果枚举

DELETE_APARTMENT_ERROR(208, "请先删除房间"),

4、抛出自定义的异常类

throw new LeaseException(ResultCodeEnum.DELETE_APARTMENT_ERROR);

 

posted @ 2025-05-11 23:17  市丸银  阅读(117)  评论(0)    收藏  举报