news 2026/6/15 17:11: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/6/15 0:28:59

美国芯片再次靠华人拯救成功,重执芯片牛耳,华人的能力得到证明

华人陈立武担任Intel的CEO仅仅9个月就宣布1.8纳米工艺取得成功&#xff0c;并率先拿出了1.8纳米生产的处理器&#xff0c;而日前陈立武再次大动作&#xff0c;主动放下身段与GPU领头羊NVIDIA合作&#xff0c;意图重振PC业务&#xff0c;此举更代表着陈立武的务实和合作精神&…

作者头像 李华
网站建设 2026/6/15 14:21:47

Spring Boot 钩子全集实战(五):ApplicationContextInitializer详解

Spring Boot 钩子全集实战&#xff08;五&#xff09;&#xff1a;ApplicationContextInitializer 详解 在上一篇中&#xff0c;我们深入剖析了 SpringApplicationRunListener.environmentPrepared() 这一关键扩展点&#xff0c;实现了环境合法性校验、启动上下文传递、多环境…

作者头像 李华
网站建设 2026/6/15 14:22:59

利用多进程提升图表模拟程序的性能

引言 在实时数据处理和图表模拟的领域,程序的响应速度和效率至关重要。特别是当我们处理大量数据并需要实时更新图表时,如何高效地利用系统资源就成为了一个关键问题。今天我们来探讨如何通过多进程来优化一个图表模拟程序的性能。 问题描述 我们有一款图表模拟程序,用于…

作者头像 李华
网站建设 2026/5/17 0:58:50

信奥赛C++提高组csp-s之欧拉回路(案例实践)

信奥赛C提高组csp-s之欧拉回路&#xff08;案例实践&#xff09; 欧拉路径 题目描述 求有向图字典序最小的欧拉路径。 输入格式 第一行两个整数 n,mn,mn,m 表示有向图的点数和边数。 接下来 mmm 行每行两个整数 u,vu,vu,v 表示存在一条 u→vu\to vu→v 的有向边。 输出格…

作者头像 李华
网站建设 2026/6/15 14:23:11

Go语言数据结构和算法(三十四)分治算法

分治算法是将一个巨大的输入分解成若干个小块.在每个小块上解决问题.然后将分段解决方案合并为全局解决方案.1.步骤:分解:将原始问题分解成一组子问题.解决子问题:递归的单独解决每个子问题.合并子问题:将子问题的解放在一起得到整个问题的解.2.应用:2.1快速排序:又称分区交互排…

作者头像 李华