博客背景 : SpringBoot SSM
dispatch ( Controller ) 层, 不会去捕获异常, 也就是意味着, 没有 try catch 语句, 走的是统一的异常捕获处理 ( 通过 filter )
所以, 业务层不能 throw Exception, 只能抛 RuntimeException, 这样 Controller 层不需要 catch
代码如下
package com.xxx.education.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xxx.education.entity.PrepareLesson;
import com.xxx.exception.BusinessRuntimeException;
/**
* @ClassName: PrepareLessonService
* @Description: PrepareLesson Service interface
* @Author: ws
* @date: 2020/1/2
* @Version: 1.0.0
*/
public interface PrepareLessonService extends IService<PrepareLesson> {
boolean deletePrepareLesson(String id) throws BusinessRuntimeException;
}
@Override
public boolean deletePrepareLesson(String id) throws BusinessRuntimeException {
boolean result = false;
try {
// 自己的业务
// ...
// ...
// ...
} catch (BusinessRuntimeException e) {
log.info(e.getMessage());
// 当前类上加上 @Transactional(rollbackFor = Exception.class)
// 事务回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new BusinessRuntimeException("事务回滚, 异常信息 : " + e.getLocalizedMessage());
}
return result;
}
package com.xxx.exception;
/**
* @ClassName BusinessRuntimeException
* @Description 业务层自定义运行时异常
* @Author ws
* @Date 2020/3/30
* @Version 1.0.0
*/
public class BusinessRuntimeException extends RuntimeException {
public BusinessRuntimeException (String message) {
super(message);
}
}