在项目中定义统一异常处理

创建统一异常处理类

import org.chz.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
   
    @ExceptionHandler(Exception.class)  //全局异常处理,执行的方法
    @ResponseBody
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail().message("全局异常处理");
    }
    
    
    @ExceptionHandler(ArithmeticException.class)    //算术异常
    @ResponseBody
    public Result error(ArithmeticException e){
        e.printStackTrace();
        return Result.fail().message("特定异常处理");
    }

    @ExceptionHandler(MyException.class)    //自定义异常,需要创建自定义异常类(如下文)
    @ResponseBody
    public Result error(MyException e){ 
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }
}

创建自定义异常类

import lombok.Data;

/**
 * 自定义全局异常类
 *
 */
@Data
public class MyException extends RuntimeException {

    private Integer code;

    private String message;

    /**
     * 通过状态码和错误消息创建异常对象
     * @param code
     * @param message
     */
    public MyException(Integer code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    /**
     * 接收枚举类型对象
     * @param resultCodeEnum
     */
    public MyException(ResultCodeEnum resultCodeEnum) {
        super(resultCodeEnum.getMessage());
        this.code = resultCodeEnum.getCode();
        this.message = resultCodeEnum.getMessage();
    }

    @Override
    public String toString() {
        return "MyException{" +
                "code=" + code +
                ", message=" + this.getMessage() +
                '}';
    }
}

在业务需要的地方抛出异常

@Api(tags = "角色管理")
@RestController
@RequestMapping("/admin/system/sysRole")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    // http://localhost:8800/admin/system/sysRole/findAll
    @ApiOperation(value = "获取全部角色列表")
    @GetMapping("/findAll")
    public Result<List<SysRole>> findAll(){
        List<SysRole> list = sysRoleService.list();
//        try {
//            int i = 10/0;
//        }catch (Exception e){
//            throw new MyException(500,"处理自定义异常");
//        }

        return Result.ok(list);
    }
posted @ 2023-07-13 22:06  ︶ㄣ演戲ㄣ  阅读(10)  评论(0)    收藏  举报