news 2026/9/20 8:21:51

使用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/9/15 5:36:03

上班是一场冷静的交易

将上班视作一场冷静的交易&#xff0c;这并非 cynicism&#xff0c;而是一种珍贵的清醒。它像一副坚固的甲胄&#xff0c;保护我们在职业的疆场上不被无谓的情绪流矢所伤&#xff0c;不被暧昧的期望绑架。我们付出标定好的时间、技能与专注&#xff0c;换取等值的报酬、经验与履…

作者头像 李华
网站建设 2026/9/18 0:38:13

解决Unity中按钮点击索引问题

在使用Unity开发游戏或应用时,经常会遇到需要为多个按钮动态添加点击事件并传递索引参数的情况。然而,这种操作在C#中可能会导致一些意想不到的问题。本文将通过一个实际例子,解释这些问题及其解决方案。 问题描述 假设我们有一个ScrollView组件,其内容包含多个Button对象…

作者头像 李华
网站建设 2026/9/15 5:36:02

python 中 try / except 详解和各类异常介绍

目录 1&#xff09;最基本形态&#xff1a;try except 运行会输出什么&#xff1f; 2&#xff09;捕获“特定异常”&#xff1a;更推荐 3&#xff09;拿到异常对象&#xff1a;看错误信息 4&#xff09;多个 except&#xff1a;按顺序匹配 5&#xff09;except 可以一次…

作者头像 李华
网站建设 2026/9/16 4:55:04

驾驶认知的本质:人类模式 vs 端到端自动驾驶

在讨论自动驾驶系统时&#xff0c;一个常见的误解是把“开车能力”等同于“驾驶智能”。事实上&#xff0c;人类驾驶与端到端自动驾驶之间的核心差异&#xff0c;并不在于动作精度或感知能力&#xff0c;而在于认知结构与任务管理模式。一、人类驾驶&#xff1a;动态任务管理的…

作者头像 李华
网站建设 2026/9/16 16:06:23

信奥赛C++提高组csp-s之拓扑排序详解

信奥赛C提高组csp-s之拓扑排序详解 一、拓扑排序基本概念 拓扑排序(Topological Sort)是对有向无环图(DAG)的一种线性排序&#xff0c;使得对于图中的每一条有向边(u, v)&#xff0c;u在排序中总是位于v的前面。 基本性质&#xff1a; 只有有向无环图(DAG)才有拓扑排序一个D…

作者头像 李华