news 2026/3/7 14:53:58

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
使用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);}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/2/24 17:10:59

今天智谱上市,成为全球大模型第一股!

今天智谱&#xff08;股票代码&#xff1a;2513.HK&#xff09;于2026年1月8日在港交所主板正式挂牌上市&#xff0c;成为"全球大模型第一股"。公司开盘报120港元&#xff0c;较发行价116.2港元上涨3.27%&#xff0c;市值达528亿港元。

作者头像 李华
网站建设 2026/3/5 3:04:13

29.useEventListener

React useEventListener 钩子:如何优雅地管理事件监听器? 在 React 应用开发中,添加和管理事件监听器是一个常见任务,但直接在组件中使用原生的 addEventListener 和 removeEventListener 可能会导致代码冗长且容易出错。useEventListener 钩子提供了一种简洁而强大的方式…

作者头像 李华
网站建设 2026/3/4 1:08:19

基于Java+SpringBoot+SSM儿童医院挂号管理系统(源码+LW+调试文档+讲解等)/儿童医院预约系统/儿童医院就诊管理系统/医院挂号管理系统/儿童医院挂号平台/儿童医院在线挂号

博主介绍 &#x1f497;博主介绍&#xff1a;✌全栈领域优质创作者&#xff0c;专注于Java、小程序、Python技术领域和计算机毕业项目实战✌&#x1f497; &#x1f447;&#x1f3fb; 精彩专栏 推荐订阅&#x1f447;&#x1f3fb; 2025-2026年最新1000个热门Java毕业设计选题…

作者头像 李华
网站建设 2026/3/5 5:49:26

Oracle数据库中的层次查询优化

在处理大型数据库中的层次查询时,性能优化是一个关键问题。本文将通过一个实际的例子,探讨如何优化Oracle数据库中使用CONNECT BY NOCYCLE PRIOR语句的查询。 问题背景 假设我们有一张名为TABLE1的表,包含客户号(CUST_NUM)、客户ID(CUST_ID)、等级(TIER)、开始日期(…

作者头像 李华
网站建设 2026/3/1 13:18:34

在Azure中实现跨订阅的AMPLS自动链接策略

在Azure环境中,管理和自动化资源链接是提升运维效率和确保安全性的关键。特别是在处理不同订阅的资源时,如何高效地实现跨订阅的自动链接是一个常见的挑战。本文将通过一个实际的案例,详细介绍如何利用Azure Policy实现Application Insights与AMPLS(Azure Monitor Private …

作者头像 李华
网站建设 2026/3/1 0:14:14

信奥赛C++提高组csp-s之欧拉回路

信奥赛C提高组csp-s之欧拉回路 一、欧拉回路是什么及其作用 欧拉回路定义 欧拉回路&#xff1a;从一个顶点出发&#xff0c;经过图中每条边恰好一次&#xff0c;最终回到起点的路径欧拉路径&#xff1a;从一个顶点出发&#xff0c;经过图中每条边恰好一次&#xff0c;最终到达…

作者头像 李华