作用
- 统一处理抛出的异常,简化异常处理
- 对前端友好,错误代码不会跑到前端,且返回统一的数据格式也方便前端统一处理
实现
- 类上添加
@ControllerAdvice
+@ResponseBody
或者@RestControllerAdvice
注解 - 方法上添加
@ExceptionHandler
注解,通过value属性指定处理的异常类型,多个异常类型用逗号分隔 - 定义统一的返回对象 如示例中的
BaseResponse
类型
示例
@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionHandlerAdvice {
/** * 系统自定义非预期异常拦截 */ @ExceptionHandler(SystemException.class)
public BaseResponse exception(SystemException e) { log.error(e.getMessage(), e);
return BaseResponse.valueOfError(-1, "系统繁忙");
}
}
```