当前位置: 首页 > news >正文

使用aop切面springmvc后抛出异常一直捕捉不到异常(抛出异常UndeclaredThrowableException类)

WebLogControllerAop这是一个切面处理类,使用的Around处理切面,有异常必须抛出,不然全局异常捕捉不到的

packagecn.geg.lifecycle.config;importcn.geg.lifecycle.util.WebLogUtils;importcn.hutool.core.collection.CollUtil;importcn.hutool.core.util.StrUtil;importcn.hutool.json.JSONObject;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Pointcut;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.stereotype.Component;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.util.Enumeration;@Aspect@ComponentpublicclassWebLogControllerAop{privatestaticfinalLoggerlog=LoggerFactory.getLogger(WebLogControllerAop.class);publicWebLogControllerAop(){}/** * 定义切点,这是一个标记方法 * cn.geg.*下的所有controller子包及方法 */@Pointcut("execution( * cn.geg.*..controller..*.*(..))")publicvoidanyMethod(){}@Around("anyMethod()")publicObjectdoAround(ProceedingJoinPointpjp)throwsThrowable{ServletRequestAttributesattributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();HttpServletRequestrequest=attributes.getRequest();HttpServletResponseresponse=attributes.getResponse();StringmethodDesc=WebLogUtils.getAspectLogDesc(pjp);log.info("========================================== Start ==========================================");log.info("URL : {}",request.getRequestURL().toString());log.info("MethodDesc : {}",methodDesc);log.info("HTTP Method : {}",request.getMethod());log.info("Class Method : {}.{}",pjp.getSignature().getDeclaringTypeName(),pjp.getSignature().getName());log.info("IP : {}",request.getRemoteAddr());try{JSONObjectheaders=newJSONObject();EnumerationheaderNames=request.getHeaderNames();while(headerNames.hasMoreElements()){StringheaderName=(String)headerNames.nextElement();StringheaderValue=request.getHeader(headerName);if(!StrUtil.isEmpty(headerValue)){headers.set(headerName,headerValue);}}log.info("Request Header : {}",headers.toJSONString(0));if(!CollUtil.isEmpty(request.getParameterMap())){log.info("Request Param : {}",com.alibaba.fastjson.JSONObject.toJSONString(request.getParameterMap()));}if(WebLogUtils.getAspectLogReq(pjp)){log.info("Request Args : {} {}",methodDesc,com.alibaba.fastjson.JSONObject.toJSONString(WebLogUtils.removeRequestAndResponse(pjp.getArgs())));}}catch(Exceptione){log.error("Request Log Print Error:{}",e.getMessage(),e);}longstartTime=System.currentTimeMillis();Objectvar11;try{Objectresult=pjp.proceed();if(WebLogUtils.getAspectLogRes(pjp)){log.info("Response Args : {} {}",methodDesc,result);}var11=result;}catch(Exceptionexception){log.info(exception.getMessage());//必须抛出异常throwexception;}finally{log.info("Time-Consuming : {} ms",System.currentTimeMillis()-startTime);log.info("=========================================== End ===========================================");}returnvar11;}}

mvc的操作,使用Exception抛出异常类为UndeclaredThrowableException,使用RunRuntimeException抛出异常类为RuntimeException

@SneakyThrows@OperLog(businessType=BusinessType.IMPORT,menuName="设备信息管理")@ApiOperation(value="导入kks码模板列表",notes="导入kks码模板列表")@PostMapping("/kksCodes")publicRuploadKksCodes(StringstationId,@RequestPart("file")MultipartFilefile){inta=0;if(a==0){//使用Exception抛出异常类为UndeclaredThrowableException,使用RunRuntimeException抛出异常类为RuntimeExceptionthrownewException("异常");}

GlobalExceptionConfig 全局异常加上UndeclaredThrowableException的处理即可

packagecn.geg.lifecycle.config;importcn.geg.lifecycle.common.R;importcn.geg.lifecycle.conts.Sys;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.validation.BindException;importorg.springframework.validation.FieldError;importorg.springframework.web.bind.MethodArgumentNotValidException;importorg.springframework.web.bind.annotation.ControllerAdvice;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ResponseBody;importjava.lang.reflect.UndeclaredThrowableException;@ControllerAdvicepublicclassGlobalExceptionConfig{privatestaticfinalLoggerlog=LoggerFactory.getLogger(GlobalExceptionConfig.class);@ExceptionHandler(value=Exception.class)@ResponseBodypublicRexceptionHandler(Exceptione){e.printStackTrace();log.error("发生异常,异常信息:{}",e.getMessage(),e);Throwablecause=e.getCause();if(causeinstanceofException){returnR.error(cause.getMessage(),Sys.SAVE_ERROR_CODE);}returnR.error(e.getLocalizedMessage(),Sys.SAVE_ERROR_CODE);}@ExceptionHandler(UndeclaredThrowableException.class)@ResponseBodypublicR<?>handleUndeclaredThrowable(UndeclaredThrowableExceptionex){Throwablecause=ex.getCause();if(causeinstanceofException){returnR.error(cause.getMessage(),Sys.SAVE_ERROR_CODE);}// 其他异常处理returnR.error(cause.getMessage(),Sys.SAVE_ERROR_CODE);}/** * 处理验证框架错误 * * @param e * @return */@ExceptionHandler(value={BindException.class,MethodArgumentNotValidException.class})@ResponseBodypublicRvalidExceptionHandler(Exceptione){log.error("发生异常,异常信息:{}",e.getMessage(),e);if(einstanceofBindException){BindExceptionbindException=(BindException)e;R<FieldError>error=R.success(bindException.getBindingResult().getFieldError());error.setErrorCode(Sys.VALIDATION_ERROR_CODE);error.setSuccess(false);returnerror;}if(einstanceofMethodArgumentNotValidException){MethodArgumentNotValidExceptionmethodArgumentNotValidException=(MethodArgumentNotValidException)e;R<FieldError>error=R.success(methodArgumentNotValidException.getBindingResult().getFieldError());error.setSuccess(false);error.setErrorCode(Sys.VALIDATION_ERROR_CODE);error.setMsg(methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage());returnerror;}returnR.error(e.getLocalizedMessage(),Sys.SAVE_ERROR_CODE);}}
http://www.jsqmd.com/news/217533/

相关文章:

  • 在Azure中实现跨订阅的AMPLS自动链接策略
  • Java Web Web足球青训俱乐部管理后台系统系统源码-SpringBoot2+Vue3+MyBatis-Plus+MySQL8.0【含文档】
  • Flask应用中的实例路径问题探讨
  • 上班是一场冷静的交易
  • 【2025最新】基于SpringBoot+Vue的师生健康信息管理系统管理系统源码+MyBatis+MySQL
  • 《斯图尔特微积分(下册)》什么时候出?带答案吗???
  • 实时语音识别回声消除技巧
  • 解决Unity中按钮点击索引问题
  • python开发中虚拟环境配置
  • Day32 >> 56、合并区间 + 738、单调递增的数字
  • 【毕业设计】SpringBoot+Vue+MySQL 社区医院信息平台平台源码+数据库+论文+部署文档
  • 驾驶认知的本质:人类模式 vs 端到端自动驾驶
  • 操作mysql常用python脚本,强到爆炸
  • Python倒计时:优雅的控制台输出
  • Java SpringBoot+Vue3+MyBatis IT交流和分享平台系统源码|前后端分离+MySQL数据库
  • SpringBoot+Vue 海滨体育馆管理系统管理平台源码【适合毕设/课设/学习】Java+MySQL
  • 数据读取瓶颈:设置PyTorch DataLoader这三个参数:num_workers / pin_memory / persistent_workers;以及如何正确它们保证程序正常运行
  • 精通plotnine:仅为特定数据组添加误差条
  • python 中 try / except 详解和各类异常介绍
  • hh蓝桥杯每日一题
  • CES 2026黄仁勋演讲:计算的炼金术(PPT版)
  • ⚡_延迟优化实战:从毫秒到微秒的性能突破[20260108165321]
  • 从“积雪深度”到“雪水当量”:寒区研究为何需要多维度的降雪数据?
  • 信奥赛C++提高组csp-s之欧拉回路
  • 信奥赛C++提高组csp-s之欧拉回路(案例实践)
  • 信奥赛C++提高组csp-s之拓扑排序详解
  • [特殊字符]_高并发场景下的框架选择:从性能数据看技术决策[20260108170044]
  • SpringBoot+Vue ONLY在线商城系统平台完整项目源码+SQL脚本+接口文档【Java Web毕设】
  • WebDriver——》常用的页面元素处理方式
  • 信奥赛C++提高组csp-s之拓扑排序(案例实践)