全局异常处理(非REST控制器代码)

问题描述 投票:0回答:2

我试图处理全局异常,但如果没有来自 REST API 的方法调用,它就无法工作。

我有以下代码

@SpringBootApplication 
public class LogReduceDemoApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(LogReduceDemoApplication.class, args);
        System.out.println(".......Started......");
        LogReduceDemoApplication.testException();
    }

    public static void testException() throws Exception {
        throw new Exception("testException...");
    }
}

异常处理程序

@ControllerAdvice
public class ExceptionHelper {

    static final Logger logger = LoggerFactory.getLogger(ExceptionHelper.class.getName());

    @ExceptionHandler(value = { NullPointerException.class,Exception.class })
    public ResponseEntity<Object> handleException(Exception ex) {
        System.out.println("Inside handleException...");
        String msg="ex="+ex+", ex.getMessage()="+ex.getMessage();
        System.out.println("Exception Msg: "+ msg);
        return new ResponseEntity<Object>(msg, HttpStatus.BAD_REQUEST);
    }
}

当我从 REST 控制器调用 LogReduceDemoApplication.testException() 方法时,它会触发异常处理程序。但是,当使用 main() 函数调用同一方法时,它不会触发异常处理程序,而是打印所有异常详细信息。

如何使用异常处理程序来处理来自主函数(而不是来自 REST 控制器)的方法调用?

java spring-boot exception spring-annotations controller-advice
2个回答
3
投票

您应该尝试使用方面。像这样的东西:

@Component
@Aspect
public class LoggingAspect {    
       
    private final Logger logger =
            LoggerFactory.getLogger(getClass().getSimpleName());               

    @Around("execution(* {YOU_PACKAGE_HERE}..*.*(..))")
    public Object someOperationAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result;
        try {
            long t1 = System.currentTimeMillis();
            logger.debug("Calling {} with args: {} ",
                    pjp.getSignature().toShortString(),
                    pjp.getArgs());
            result = pjp.proceed();
            double duration = (System.currentTimeMillis() - t1) / 1000.;
            logger.debug("{} - Time elapsed: {}sec",
                    pjp.getSignature().toShortString(), duration);
        } catch (Throwable ex) {
            logger.warn("When call {} with args: {} Exception thrown: {}",
                    pjp.getSignature().toShortString(),
                    pjp.getArgs(), ex.getMessage());
            throw ex;
        }
        return result;
    }

}

或者如果您只需要捕获异常,则使用 @AfterThrowing 而不是 @Around。

    @AfterThrowing(pointcut="execution(* {YOU_PACKAGE_HERE}..*.*(..)))", throwing="theExc")
    public void afterThrowingAdvice(JoinPoint theJoinPoint, Throwable theExc) {

        String method = theJoinPoint.getSignature().toShortString();
        System.out.println("\n=====>>> Executing @AfterThrowing on method: " + method);
    
        // log the exception
        System.out.println("\n=====>>> The exception is: " + theExc);    
    }

0
投票

你不能。这也没有道理。

@ExceptionHandler
方法返回一个
ResponseEntity
,在 REST 上下文之外没有任何意义。

© www.soinside.com 2019 - 2024. All rights reserved.