javascript
java打印的globa类l_Spring异常集中处理和日志集中打印
使用@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處理,返回服務器異常,所有異常均打印日志
總結
以上是生活随笔為你收集整理的java打印的globa类l_Spring异常集中处理和日志集中打印的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java char 空_2020重新出发
- 下一篇: layui上传文件请求接口异常_Spri