直接上代码:
重点:
@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());
}
}
}