首页 > 解决方案 > Springboot,如何记录和捕获beaninstantiationexception?

问题描述

我有一个自动装配的构造函数,其中从application.properties文件加载参数。我在构造函数中随机看到 NPE 并BeanInstantiationException因此得到 a 。

是否可以拦截此故障,以便我可以添加日志并终止运行此代码的 pod?结果,我的应用程序无限期挂起。

  @Autowired
  public GraphClient(
      @Value("${thing1}") String t1,
      @Value("${thing2}") int t2,
      @Value("${thing3}") boolean t3,
      @Value("${thing4}") boolean t4,
      @Value("${thing5}") int t5) {

标签: javaspring-boot

解决方案


使用ResponseEntityExceptionHandler类将使我们能够捕获应用程序中发生的任何异常。

@ControllerAdvice
public class AppExceptionHandler extends ResponseEntityExceptionHandler {
    
    @ExceptionHandler(BeanInstantiationException.class)
    public ResponseEntity catchBeanInstantiationException() {
        // add log
        // do anything you want
    }

}


推荐阅读