使用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);

  }

}
相关推荐
云烟成雨TD5 小时前
Spring AI 1.x 系列【51】可观测性技术选型
java·人工智能·spring
unicrom_深圳市由你创科技5 小时前
基于Spring AI框架的RAG应用
人工智能·spring·机器学习
七老板的blog7 小时前
当 Spring StateMachine 遇见大模型:构建工业级 AI 写作流水线
java·人工智能·spring
云烟成雨TD7 小时前
Spring AI 1.x 系列【46】MCP Security 模块
java·人工智能·spring
小旭95278 小时前
Spring AI Alibaba 从入门到实战:一站式掌握企业级 AI 应用开发
java·人工智能·spring
云烟成雨TD9 小时前
Spring AI 1.x 系列【50】可观测性:接入 Prometheus + Grafana
人工智能·spring·prometheus
phltxy11 小时前
MCP 从协议到 Spring AI 实战
人工智能·spring·oracle
Volunteer Technology13 小时前
SpringSecurity请求流转的本质
java·spring
云烟成雨TD14 小时前
Spring AI 1.x 系列【42】MCP 服务端 Spring Boot 启动器
java·人工智能·spring
云烟成雨TD14 小时前
Spring AI 1.x 系列【38】模型上下文协议(MCP)
java·人工智能·spring