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

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

java 复制代码
package cn.geg.lifecycle.config;

import cn.geg.lifecycle.util.WebLogUtils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Aspect
@Component
public class WebLogControllerAop {
    private static final Logger log = LoggerFactory.getLogger(WebLogControllerAop.class);

    public WebLogControllerAop() {
    }

    /**
     * 定义切点,这是一个标记方法
     * cn.geg.*下的所有controller子包及方法
     */
    @Pointcut("execution( * cn.geg.*..controller..*.*(..))")
    public void anyMethod() {
    }

    @Around("anyMethod()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String methodDesc = 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 {
            JSONObject headers = new JSONObject();
            Enumeration headerNames = request.getHeaderNames();

            while(headerNames.hasMoreElements()) {
                String headerName = (String)headerNames.nextElement();
                String headerValue = 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 (Exception e) {
            log.error("Request Log Print Error:{}",e.getMessage(),e);
        }

        long startTime = System.currentTimeMillis();

        Object var11;
        try {
            Object result = pjp.proceed();
            if (WebLogUtils.getAspectLogRes(pjp)) {
                log.info("Response Args  : {} {}", methodDesc, result);
            }

            var11 = result;
        } catch (Exception exception) {
            log.info(exception.getMessage());
            //必须抛出异常
            throw exception;
        } finally {
            log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
            log.info("=========================================== End ===========================================");
        }

        return var11;
    }
}

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

java 复制代码
    @SneakyThrows
    @OperLog(businessType = BusinessType.IMPORT, menuName = "设备信息管理")
    @ApiOperation(value = "导入kks码模板列表", notes = "导入kks码模板列表")
    @PostMapping("/kksCodes")
    public R uploadKksCodes(String stationId, @RequestPart("file") MultipartFile file){

        int a=0;
        if(a==0){
            //使用Exception抛出异常类为UndeclaredThrowableException,使用RunRuntimeException抛出异常类为RuntimeException
            throw new Exception("异常");
        }

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

java 复制代码
package cn.geg.lifecycle.config;

import cn.geg.lifecycle.common.R;
import cn.geg.lifecycle.conts.Sys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.UndeclaredThrowableException;

@ControllerAdvice
public class GlobalExceptionConfig {

  private static final Logger log = LoggerFactory.getLogger(GlobalExceptionConfig.class);

  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public R exceptionHandler(Exception e) {
    e.printStackTrace();
    log.error("发生异常,异常信息:{}",e.getMessage(),e);
    Throwable cause = e.getCause();
      if (cause instanceof Exception) {
        return R.error(cause.getMessage(),Sys.SAVE_ERROR_CODE);
      }
    return R.error(e.getLocalizedMessage(), Sys.SAVE_ERROR_CODE);
  }

  @ExceptionHandler(UndeclaredThrowableException.class)
  @ResponseBody
  public R<?> handleUndeclaredThrowable(UndeclaredThrowableException ex) {
    Throwable cause = ex.getCause();
    if (cause instanceof Exception) {
      return R.error(cause.getMessage(),Sys.SAVE_ERROR_CODE);
    }
    // 其他异常处理
    return R.error(cause.getMessage(), Sys.SAVE_ERROR_CODE);
  }

  /**
   * 处理验证框架错误
   * 
   * @param e
   * @return
   */
  @ExceptionHandler(value = { BindException.class, MethodArgumentNotValidException.class })
  @ResponseBody
  public R validExceptionHandler(Exception e) {
    log.error("发生异常,异常信息:{}",e.getMessage(),e);
    if (e instanceof BindException) {
      BindException bindException = (BindException) e;
      R<FieldError> error = R.success(bindException.getBindingResult().getFieldError());
      error.setErrorCode(Sys.VALIDATION_ERROR_CODE);
      error.setSuccess(false);
      return error;
    }

    if (e instanceof MethodArgumentNotValidException) {
      MethodArgumentNotValidException methodArgumentNotValidException = (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());
      return error;
    }
    return R.error(e.getLocalizedMessage(), Sys.SAVE_ERROR_CODE);

  }

}
相关推荐
NE_STOP21 小时前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
玹外之音2 天前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉2 天前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP2 天前
springMVC-常见视图组件与RESTFul编程风格
spring
what丶k3 天前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
NE_STOP3 天前
springMVC-获取前端请求的数据与三个作用域
spring
莫寒清3 天前
Spring MVC:@PathVariable 注解详解
java·spring·mvc
-大头.3 天前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(1)
spring
莫寒清3 天前
Apache Tika
java·人工智能·spring·apache·知识图谱