Spring Boot 入门整合目录
自定义异常处理类
实现自定义异常处理需要继承RuntimeException类
import lombok.Data;
@Data
public class InfoException extends RuntimeException {
private Integer code;
private String message;
public InfoException(Integer code,String message) {
this.code = code;
this.message = message;
}
}
配置全局异常处理
- @ControllerAdvice
- @ResponseBody
- @ExceptionHandler
@RestControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(value = InfoException.class)//拦截指定异常
public Map<String,Object> errorHandler(InfoException infoException) {
Map<String,Object> map = new HashMap<>();
map.put("code",infoException.getCode());
map.put("message",infoException.getMessage());
return map;
}
}
测试异常处理
@Service
public class InfoServiceImpl implements InfoService {
@Resource
private InfoDao infoDao;
@Transactional(rollbackFor = Exception.class)
@Override
public void updateInfo(Info info) throws Exception {
//先删除 在更新
infoDao.deleteInfo("2");
if (1==1) {
throw new InfoException(8001,"事务回滚");
}
infoDao.updateInfo("100");
}
}
相应结果: