1.自定义异常
继承异常
2.全局管理
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 处理自定义业务异常
*
* @param request 请求
* @param e 自定义业务异常
* @return map
* @author ZhaoQingDong
*/
@ExceptionHandler(value = BusinessException.class)
public R businessException(HttpServletRequest request, BusinessException e) {
log.error(request.getRequestURL() + ":业务异常 ========> code:{}, msg:{}", e.getCode(), e.getMsg());
return R.error(e.getCode(), e.getMsg());
}
/**
* 处理参数校验异常一
*
* @param request 请求
* @param e 参数校验异常一
* @return map
* @author ZhaoQingDong
*/
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R methodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
log.error(request.getRequestURL() + ":请求参数异常 ========> :{}", e.getMessage());
BindingResult result = e.getBindingResult();
Map<String, String> map = new HashMap<>();
if (result.hasErrors()) {
List<FieldError> fieldErrors = result.getFieldErrors();
fieldErrors.forEach(error -> map.put(error.getField(), error.getDefaultMessage()));
}
e.printStackTrace();
return R.error(BusinessExceptionEnum.PARAM_NOT_MATCH.getCode(), BusinessExceptionEnum.PARAM_NOT_MATCH.getMsg()).putData(map);
}
/**
* 处理参数校验异常二
*
* @param request 请求
* @param e 参数校验异常二
* @return map
* @author ZhaoQingDong
*/
@ExceptionHandler(value = ConstraintViolationException.class)
public R constraintViolationException(HttpServletRequest request, ConstraintViolationException e) {
log.error(request.getRequestURL() + ":请求参数异常 ========> :{}", e.getMessage());
Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
Map<String, String> map = new HashMap<>();
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
map.put(constraintViolation.getPropertyPath().toString(), constraintViolation.getMessageTemplate());
}
e.printStackTrace();
return R.error(BusinessExceptionEnum.PARAM_NOT_MATCH.getCode(), BusinessExceptionEnum.PARAM_NOT_MATCH.getMsg()).putData(map);
}
/**
* ID不存在,查询结果为空
*
* @param request 请求
* @param e ID不存在,查询结果为空异常
* @author 赵庆东 2021-10-02 09:08
*/
@ExceptionHandler(value = EmptyResultDataAccessException.class)
public R emptyResultDataAccessException(HttpServletRequest request, EmptyResultDataAccessException e) {
log.error(request.getRequestURL() + ":ID不存在异常 ========> :{}", e.getMessage());
return R.error(BusinessExceptionEnum.RESULT_NOT_EXIST.getCode(), BusinessExceptionEnum.RESULT_NOT_EXIST.getMsg()).putData(e.getMessage());
}
}
@RestControllerAdvice
@ @ExceptionHandler(value = EmptyResultDataAccessException.class)
本文档介绍了如何使用Spring MVC全局异常处理,展示了如何捕获并处理自定义 BusinessException、参数校验异常以及特定场景如ID不存在的EmptyResultDataAccessException。通过log记录错误,并返回统一的错误响应格式。
1151

被折叠的 条评论
为什么被折叠?



