news 2026/4/16 16:27:26

使用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/4/16 11:13:41

MATLAB实现流形正则化主题模型LapPLSI算法详解

在文本挖掘和主题建模领域,传统的pLSA(Probabilistic Latent Semantic Analysis)和LDA模型假设文档独立同分布,但现实中文档往往存在内在关联(如引用关系、相似内容或社交网络)。为了利用这些文档间的流形结构,研究者提出了Laplacian Probabilistic Latent Semantic Ind…

作者头像 李华
网站建设 2026/4/16 14:50:03

操作mysql常用python脚本,强到爆炸

1.导出数据库指定表的所有字段(含有字段注释)和数据导出结果如下#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MySQL数据导出工具 - 修复元组索引问题 """import pandas as pd import pymysql import openpyxl from openpyxl.utils impo…

作者头像 李华
网站建设 2026/4/16 14:50:17

前后端分离学科竞赛管理系统|SpringBoot+Vue+MyBatis+MySQL完整源码+部署教程

摘要 随着信息技术的快速发展&#xff0c;学科竞赛管理系统的信息化和智能化需求日益增长。传统的学科竞赛管理模式依赖人工操作&#xff0c;效率低下且容易出错&#xff0c;难以满足大规模竞赛活动的需求。为了解决这一问题&#xff0c;设计并实现一个基于前后端分离架构的学科…

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

DSP算法学习

都是以QPSK为例针对不同的qam信号&#xff0c;一些算法可能不同&#xff0c;还需读者再去学习从IQ时延对准-IQ不平衡-粗色散补偿-自适应均衡解复用-频偏估计与补偿-载波相位恢复

作者头像 李华
网站建设 2026/4/16 14:50:21

ai-agent 一个强大的辅助工具

随着ai的大热&#xff0c;如何更好的利用ai&#xff0c;而不单单作为知识的查询。如果它能帮我们设计测试用例&#xff0c;执行用例&#xff0c;并给出结果&#xff0c;甚至可以帮我们开发&#xff0c;是不是一个梦中情tool。 这不单单是幻想&#xff0c;目前不少大厂已经实现&…

作者头像 李华
网站建设 2026/4/16 13:00:41

[特殊字符]_微服务架构下的性能调优实战[20260108162541]

作为一名经历过多个微服务架构项目的工程师&#xff0c;我深知在分布式环境下进行性能调优的复杂性。微服务架构虽然提供了良好的可扩展性和灵活性&#xff0c;但也带来了新的性能挑战。今天我要分享的是在微服务架构下进行性能调优的实战经验。 &#x1f4a1; 微服务架构的性…

作者头像 李华