调用APIGatewayProxyRequestEvent的getRequestContext时出现空指针异常 - AWS Lambda(Java)
问题分析与解决
你遇到的空指针异常是因为input参数为null时调用了input.getRequestContext(),而异常在构建阶段抛出,说明构建过程中存在自动执行handleRequest方法的环节(比如单元测试、预构建校验),但该环节没有传入有效的APIGatewayProxyRequestEvent实例。
解决步骤:
1. 给handleRequest方法添加空值校验
在调用input.getRequestContext()前先判断input是否为空,避免空指针:
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("X-Custom-Header", "application/json"); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() .withHeaders(headers); // 新增空值校验 if (input == null) { return response .withStatusCode(400) .withBody("{\"error\":\"请求参数不能为空\"}"); } try { System.out.println("*** REQUEST CONTEXT ***"); System.out.println(input.getRequestContext()); final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); String output = String.format("{ \"message\": \"Hello There!\", \"location\": \"%s\" }", pageContents); return response .withStatusCode(200) .withBody(output); } catch (IOException e) { return response .withBody("{}") .withStatusCode(500); } }
2. 检查构建流程中的测试环节
如果是构建时运行单元测试导致的异常,需要在测试代码中构造有效的APIGatewayProxyRequestEvent对象:
// 示例单元测试代码(使用JUnit和Mockito) import org.junit.Test; import static org.mockito.Mockito.mock; public class AppTest { @Test public void testHandleRequest() { App app = new App(); // 构造输入事件 APIGatewayProxyRequestEvent input = new APIGatewayProxyRequestEvent(); // 可选:设置requestContext内容 RequestContext requestContext = new RequestContext(); input.setRequestContext(requestContext); // 模拟Context对象 Context context = mock(Context.class); // 调用方法 APIGatewayProxyResponseEvent response = app.handleRequest(input, context); // 验证结果(根据需求添加断言) assert response.getStatusCode() == 200; } }
3. SAM本地测试时提供正确的事件模板
如果是使用sam local invoke本地测试,需要创建包含APIGateway事件结构的JSON文件(比如event.json),示例结构:
{ "requestContext": { "requestId": "test-request-id", "identity": { "sourceIp": "127.0.0.1" } }, "headers": { "Content-Type": "application/json" } }
然后执行命令:
sam local invoke -e event.json
内容的提问来源于stack exchange,提问作者El_bosteador
相关产品推荐
相关产品推荐

