java的全局异常拦截

直接上代码:

重点:

@ControllerAdvice加上这个标签就可以进行全局的一个异常处理

@ControllerAdvice
public class GlobalExceptionHandler {
	//返回值为json
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public AppResponseJson defaultErrorHandler(HttpServletRequest request, Exception ex) {
		
		if (ex instanceof ValidationException || ex instanceof MethodArgumentNotValidException
				|| ex instanceof BindException) {
			ex.printStackTrace();
			return AppResponseJson.errorByOwnCode(AppHttpCode.PARAM_ERROR, "参数错误");
		} else if (ex instanceof SessionTimeoutException) {
			return AppResponseJson.errorByOwnCode(AppHttpCode.PLEASE_LOGIN, "请重新登录");
		} else if (ex instanceof ServiceException) {
			ex.printStackTrace();
			return AppResponseJson.errorByOwnCode(AppHttpCode.SERVICE_ERROR, ex.getMessage());
		} else if (ex instanceof NullPointerException) {
			ex.printStackTrace();
			return AppResponseJson.errorByOwnCode(AppHttpCode.FAILE, "空指针");
		} else {
			ex.printStackTrace();
			return AppResponseJson.errorByOwnCode(AppHttpCode.FAILE, ex.getMessage());
		}
	}

}

    原文作者:许你一世繁华99
    原文地址: https://blog.csdn.net/qq_37322804/article/details/122072472
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞