基于@ControllerAdvice注解的Controller层的全局异常统一处理
定义错误信息enums
建立返回信息枚举enums来统一管理返回的信息
package com.main.enums;
import lombok.Getter;
@Getter
public enum ResultEnum {
//基础
UNKONW_ERROR(-1,"未知错误"),
SUCCESE(0,"成功"),
//College系列报错,系列号:1
COLLEGE_NOT_EXIST(11,"不存在该系"),
COLLEGE_NAME_ERROR(12,"系名不符合规定")
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
定义自己的异常
创建自己的Exception继承自RuntimeException
package com.main.exception;
import com.main.enums.ResultEnum;
import lombok.Data;
@Data
public class CollegeException extends RuntimeException{
private Integer code;
public CollegeException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
}
抛出自定义异常
//Service层抛出异常
public CollegeDao findOne(String collegeId){
CollegeDao collegeDao = repository.findById(collegeId).orElse(null);
if (collegeDao == null){
throw new CollegeException(ResultEnum.COLLEGE_NOT_EXIST);
}
return collegeDao;
}
//抛出表单验证的异常
@PostMapping("/")
public ResultVO save(@Validated CollegeForm collegeForm, BindingResult bindingResult){
if(bindingResult.hasErrors()){
throw new CollegeException(ResultEnum.PARA_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
}
return ResultVOUtil.succese(collegeService.save(collegeForm));
}
异常捕获
创建ExceptionHandle捕获Controller抛出的异常进行处理
- 捕获自定义异常
@ControllerAdvice
public class CollegeExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(CollegeExceptionHandler.class);
@ResponseBody
@ExceptionHandler(value = CollegeException.class)
public ResultVO handler(CollegeException e){
logger.info(e.getMessage());
return ResultVOUtil.error(e.getCode(),e.getMessage());
}
}
- 捕获其他未知的系统异常
@ControllerAdvice
public class UnknownExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(UnknownExceptionHandler.class);
@ResponseBody
@ExceptionHandler(Exception.class)
public ResultVO handler(Exception e){
logger.error(e.getMessage());
return ResultVOUtil.error(ResultEnum.UNKONW_ERROR.getCode(),ResultEnum.UNKONW_ERROR.getMsg());
}
}
完成统一异常处理,即使报错也能返回统一的数据格式