我正在尝试 AWS Lambda,并尝试使用 JSON 消息引发异常,因此我使用 Gson 库来构建 JSON。
问题在于,当在AWS Lambda中运行它时,它找不到库的Gson类。在本地,它可以正常工作。
这是 AWS Lambda 抛出的错误:
"errorMessage": "com/google/gson/Gson",
"errorType": "java.lang.NoClassDefFoundError",
这是代码:
public class LambdaExecutor {
public void handler(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
LambdaExceptionHandler lambdaExceptionHandler = new LambdaExceptionHandler();
lambdaExceptionHandler.setId("134");
lambdaExceptionHandler.setErrorType("Test error");
lambdaExceptionHandler.setMessage("Error in the TestLambda execution");
lambdaExceptionHandler.addError("Error into the lambda");
lambdaExceptionHandler.addError("Because it must fail epically");
lambdaExceptionHandler.throwException();
outputStream.write("Is okey :/" .getBytes());
}
}
这是 pom:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>aws-lambda</artifactId>
<version>1.0</version>
<name>AWS Lambda</name>
<description>AWS TEST</description>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.2.0</version>
<type>jar</type>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.0-M1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
</project>
最佳答案
好的,我可以通过在 pom 中添加插件 maven-shade-plugin 来修复它。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<shadedArtifactAttached>true</shadedArtifactAttached>
<shadedClassifierName>lambda</shadedClassifierName>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
关于java - aws lambda 找不到 Gson 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51543823/