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

  }

}
相关推荐
u01040583618 小时前
企业微信自建应用权限模型与 RBAC 在 Spring Security 中的映射
java·spring·企业微信
qq_124987075319 小时前
基于SpringCloud的分布式演唱会抢票系统(源码+论文+部署+安装)
分布式·spring·spring cloud·毕业设计·计算机毕业设计
華勳全栈1 天前
两天开发完成智能体平台
java·spring·go
alonewolf_991 天前
Spring MVC重点功能底层源码深度解析
java·spring·mvc
芒克芒克1 天前
本地部署SpringBoot项目
java·spring boot·spring
小突突突1 天前
Spring框架中的单例bean是线程安全的吗?
java·后端·spring
sww_10261 天前
Spring-AI和LangChain4j区别
java·人工智能·spring
YDS8291 天前
SpringCloud —— MQ的可靠性保障和延迟消息
后端·spring·spring cloud·rabbitmq
蓝程序1 天前
Spring AI学习 程序接入大模型(HTTP接入)
java·spring