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

  }

}
相关推荐
萧瑟余晖7 小时前
Java深入解析篇十七之Spring Security
java·开发语言·spring
Flittly13 小时前
【雕虫大技】Agent 动态 Skill 供应链安全加固(二):执行隔离沙箱实战
java·spring boot·spring
BUG指挥官1 天前
Sa-Token和Spring Security对比
java·后端·spring
geminigoth1 天前
Spring AI Alibaba 入门开发一(备份)
java·人工智能·spring
xbgRS2 天前
spring整合mybaits
java·spring·mybatis
ruleslol2 天前
静态依赖注入 VS 动态依赖查询
spring
墨雨晨曦882 天前
Spring AI总结
java·人工智能·spring
白仑色2 天前
Spring Boot 从切面统一控制事务
java·spring boot·aop·spring事务
用户3126874877202 天前
Spring Boot 异常处理到底怎么玩的?从 DispatcherServlet 到全局兜底的全链路拆解
spring
不才不才不不才2 天前
Spring 源码系列(17): HandlerMapping 与 HandlerAdapter 两大体系
java·后端·spring