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);
// 統(tǒng)一返回值
AppResponse response = new AppResponse();
response.setFail("服務(wù)器錯(cuò)誤");
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;
}
}
對(duì)于需要給前臺(tái)返回特定錯(cuò)誤信息的異常,手動(dòng)拋出CustomException,并添加錯(cuò)誤信息,通過(guò)handleCustomException返回,其他異常信息通過(guò)handleException處理,返回服務(wù)器異常,所有異常均打印日志
總結(jié)
以上是生活随笔為你收集整理的java打印的globa类l_Spring异常集中处理和日志集中打印的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java char 空_2020重新出发
- 下一篇: layui上传文件请求接口异常_Spri