Java笔记-25、Web后端实战实战内容
一些问题记录。
删除班级-自定义异常+全局异常处理器
如果该班级下关联的有学生,是不允许删除的,并提示错误信息:"班级下有学生, 不能直接删除"。
首先自定义异常实体类,继承RuntimeExcption:
public class ExistStudentException extends RuntimeException{
public ExistStudentException(String message){
super(message);
}
}
然后在全局异常处理器中添加对自定义异常的处理:
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ExistStudentException.class)
public Result handleExistStudentException(ExistStudentException e){
log.error("出现依赖性错误", e);
return Result.error("班级下有学生, 不能直接删除");
}
}
在ClazzServiceImpl中写逻辑,当有学生还在班级下,抛出异常:
@Override
public void deteleById(Integer id) {
if(studentMapper.countByClazzId(id) > 0){
throw new ExistStudentException("班级下有学生,不能直接删除");
}
clazzMapper.deleteById(id);
}

浙公网安备 33010602011771号