@ControllerAdvice注解,可以用于定义@ExceptionHandle,@InitBinder,@ModelAttribute,并应用到所有的@ResquestMapping中。
请看代码:
/**
统一异常处理类
捕获程序所有异常,针对不同异常,采取不同的处理方式
@author zjjlive)
@version 1.0
@website https://www.foreknow.me
@date 2018/4/24 14:37
-
@since 1.0
*/
@ControllerAdvice
public class ExceptionHandleController {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandleController.class);@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseVO handle(Throwable e) {
if (e instanceof ZhydException) {
return ResultUtil.error(e.getMessage());
}
if (e instanceof UndeclaredThrowableException) {
e = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
}
ResponseStatus responseStatus = ResponseStatus.getResponseStatus(e.getMessage());
if (responseStatus != null) {
LOGGER.error(responseStatus.getMessage());
return ResultUtil.error(responseStatus.getCode(), responseStatus.getMessage());
}
e.printStackTrace(); // 打印异常栈
return ResultUtil.error(CommonConst.DEFAULT_ERROR_CODE, ResponseStatus.ERROR.getMessage());
}
}