1.自定义异常概述
- 当在某一些特殊情况下,JDK自带的异常无法准确描述异常情况时,采用自己定义异常类的方式封装异常信息。
2. 步骤:
- 申明一个异常处理类
- 异常处理类继承RuntimeException类
- 编写一个带参的构造器
3.实例
/**
* 自定义异常类
*/
public class CustomException extends RuntimeException{
public CustomException(String message){
super(message);
}
}
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
@Autowired
private DishService dishService;
@Autowired
private SetmealService setmealService;
/**
* 根据id删除,删除前根据条件判断
*
* @param id
*/
@Override
public void remove(Long id) {
LambdaQueryWrapper<Dish> lambdaCategory = new LambdaQueryWrapper();
//添加查询条件,根据分类id进行查询
lambdaCategory.eq(Dish::getCategoryId, id);
int count = dishService.count(lambdaCategory);
System.out.println(count+"!!!");
//查询当前分页是否关联了菜品,如果关联,抛出一个业务异常
if (count > 0) {
//已经关联了菜品,抛出一个业务异常
throw new CustomException("当下分类关联了菜品,不能删除");
}
// 查询当前分页是否管理了套餐,如果关联抛出一个异常
LambdaQueryWrapper<Setmeal> lambdaQuerySetmeal = new LambdaQueryWrapper();
//添加查询条件,根据分类id查询
lambdaQuerySetmeal.eq(Setmeal::getCategoryId, id);
int count1 = setmealService.count(lambdaQuerySetmeal);
if (count1 > 0) {
//已经关联了套餐, 抛出一个业务异常
throw new CustomException("当下分类关联了套餐,不能删除");
}
//正常删除分类
setmealService.removeById(id);
}
}
4.结果: