使用@ControllerAdvice和@ExceptionHandler处理Controller层的异常:
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
// 记录日志
LOGGER.error(e.getMessage(), e);
// 统一返回值
AppResponse response = new AppResponse();
response.setFail("服务器错误");
return response;
}
/**
* 处理自定义异常
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
@ResponseBody
AppResponse handleCustomException(CustomException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
}
对于需要给前台返回特定错误信息的异常,手动抛出CustomException,并添加错误信息,通过handleCustomException返回,其他异常信息通过handleException处理,返回服务器异常,所有异常均打印日志