springboot 自定义异常 全局异常处理器

创建自定义异常类,继承 RuntimeException 类

1 public class CustomException extends RuntimeException{
2     public CustomException(String message){
3         super(message);
4     }
5 }

在指定情况下抛出该异常,代码如下:

 

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    DishSercice dishSercice;
    @Autowired
    SetmealService setmealService;
    /**
     * 根据id删除分类,删除之前要先判断该分类是否已经关联菜品或套餐
     * @param id
     */
    @Override
    public void remove(Long id) {
        QueryWrapper<Dish> dishQueryWrapper=new QueryWrapper<>();
        dishQueryWrapper.eq("category_id",id);
        long count1=dishSercice.count(dishQueryWrapper);
        if(count1>0){
            //已关联菜品,抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品,不能删除");
        }
        QueryWrapper<Setmeal> setmealQueryWrapper=new QueryWrapper<>();
        setmealQueryWrapper.eq("category_id",id);
        long count2 = setmealService.count(setmealQueryWrapper);
        if(count2>0){
            //已关联套餐,抛出一个业务异常
            throw new CustomException("当前分类下关联了套餐,不能删除");
        }

        //没出现异常,正常删除分类
        super.removeById(id);
    }
}

 

异常抛出后,进入到全局异常处理器,执行对该异常的处理方法

全局异常处理器:

/**
 * 全局异常处理
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
public class GlobalExceptionHandler {
    /*
    异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split=ex.getMessage().split(" ");
            String msg=split[2]+" 已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    /*
    异常处理方法(针对自定义CustomException异常)
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }
}

 

 

 

 

 


 

posted @ 2023-06-28 14:13  愿你所盼皆入怀  阅读(55)  评论(0)    收藏  举报