首页 > 解决方案 > { "errorType": "java.lang.ExceptionInInitializerError" } 在 AWS Lambda 函数中

问题描述

我有一项在 SpringBoot 中开发并要部署在 AWS 中的服务。在 LambdaHandler 中,给出了 Spring Applucation 类名称,以便在 AWS 环境中运行 SpringBoot 应用程序。

但是,当我尝试通过以 JSON 格式提供 i/p 作为测试事件并尝试在调用 Lambda 函数时将记录插入数据库时​​,在 AWS Lambda 控制台中出现以下错误

{
  "errorMessage": "Error loading class com.example.lambda.LambdaHandler",
  "errorType": "java.lang.ExceptionInInitializerError"
}

这是我的 LambdaHandler 类

public class LambdaHandler implements RequestHandler<AwsProxyRequest, AwsProxyResponse> {

    private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;

    static {
        try {
            handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(SpringBootApplication.class);
        } catch (ContainerInitializationException e) {
            // if we fail here. We re-throw the exception to force another cold start
            e.printStackTrace();
            throw new RuntimeException("Could not initialize Spring Boot Application", e);
        }
    }

    @Override
    public AwsProxyResponse handleRequest(AwsProxyRequest awsProxyRequest, Context context) {
        return handler.proxy(awsProxyRequest, context);
    }
}

这是我的主要应用程序类

  public class SpringBootApplication {

        public static void main(String[] args) {

            SpringApplication.run(SpringBootApplication.class, args);
        }

}

标签: javamavenspring-bootaws-lambda

解决方案


在静态上下文中引发的异常会导致此错误。

将您的代码更改为以下内容,以便您首先了解它引发异常的原因,然后解决该错误:

. . .
static {
    try {
        handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(SpringBootApplication.class);
    } catch (Exception e) {
        // if we fail here. We re-throw the exception to force another cold start
        e.printStackTrace();
        throw new RuntimeException("Could not initialize Spring Boot Application", e);
    }
}
. . .

静态加载东西时要小心。


推荐阅读