转自:今日头条作者【瞎胡佛】https://www.toutiao.com/i6898572122302513676/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1×tamp=1607903554&app=news_article&utm_source=weixin&utm_medium=toutiao_android&use_new_style=1&req_id=202012140752340101300361404DF616E4&group_id=6898572122302513676
全局异常处理
创建一个 GlobalExceptionHandler 类,使用 @RestControllerAdvice(增强型控制器) 注解就可以定义出异常通知类,默认只会处理controller层抛出的异常,如果需要处理service层的异常,我们可以自定义自己的异常类,进行捕捉
我们在在定义的方法中添加上 @ExceptionHandler 即可实现全局异常异常的捕
ControllerAdvice 和 RestControllerAdvice的区别
@ControllerAdvice 和 @RestControllerAdvice都是对Controller进行增强的,可以全局捕获spring mvc抛的异常。
@RestControllerAdvice = ControllerAdvice + ResponseBody
spring官方文档 主要配合@ExceptionHandler使用,统一处理异常情况
/**
* controller 异常处理
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理自定义异常
*
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
public Result handlerImCustomException(CustomException e) {
log.error("自定义异常:{}", e.getMessage(), e);
return new Result().buildFail(e);
}
/**
* 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常,详情继续往下看代码
*
* @param e
* @return
*/
@ExceptionHandler(BindException.class)
public Result BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
log.error("请求校验异常 BindException message:{} exception:{}", message, e.getMessage(), e);
return new Result().buildFail(message);
}
/**
* 处理参数校验异常
*
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
log.error("校验参数异常 message:{} exception:{}", message, e.getMessage(), e);
return new Result().buildFail(message);
}
/**
* 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
*/
@ExceptionHandler(ConstraintViolationException.class)
public Result handlerConstraintViolationException(ConstraintViolationException e) {
String message =
e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
log.error("校验参数异常 message:{} exception:{}", message, e.getMessage(), e);
return new Result().buildFail(message);
}
/**
* 其他异常处理
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
public Result handler(Exception e) {
log.error("系统异常", e);
return new Result().buildFail(CustomExceptionEnum.FAIL);
}
}
###总结结