You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust开发的AWS Lambda静默失败:执行main但未调用handler

问题诊断与解决方案

核心问题:Handler配置错误

你的template.yml中Lambda函数的Handler字段设置为bootstrap.is.real.handler,这是错误的。对于provided.al2运行时,Lambda会直接执行你上传的二进制文件(这里是bootstrap),不需要指定额外的handler路径。错误的Handler配置会导致Lambda无法正确触发你的业务逻辑,只会启动进程但不会调用search函数,这就是为什么你只看到in main now!却看不到hello, logs!的原因。

修复步骤:

修改template.yml中HelloRustFunction的Handler字段:

Handler: bootstrap

次要问题:事件类型不匹配

当前search函数接收的是LambdaEvent<Option<String>>,但API Gateway触发Lambda时,传入的事件是标准的API Gateway请求格式(包含body、headers、requestContext等字段),不是简单的字符串。即使修复了Handler配置,反序列化也会失败,导致函数报错。

修复步骤:

  1. 添加lambda_http依赖(兼容lambda_runtime 0.7版本)到Cargo.toml:
lambda_http = "0.7.3"
  1. 修改search.rs,使用API Gateway专用的事件类型:
use lambda_http::{ApiGatewayProxyRequest, ApiGatewayProxyResponse, Error};
use serde_json::json;

pub async fn search(event: ApiGatewayProxyRequest) -> Result<ApiGatewayProxyResponse, Error> {
    eprintln!("hello, logs!");

    Ok(ApiGatewayProxyResponse {
        status_code: 200,
        headers: vec![("Content-Type".to_string(), "application/json".to_string())].into_iter().collect(),
        body: Some(json!({"message": "hello, world!"}).to_string()),
        is_base64_encoded: false,
    })
}
  1. 同时修改main.rs中的handler类型适配:
use hello::search::search;
use lambda_http::{run, service_fn, Error};

#[tokio::main]
async fn main() -> Result<(), Error> {
    eprintln!("in main now!");
    let handler = service_fn(search);

    match run(handler).await {
        Ok(()) => eprintln!("Lambda handler exited successfully!"),
        Err(err) => eprintln!("Lambda handler failed: {}", err),
    }

    Ok(())
}

其他验证点

  • 重新构建部署:修改配置和代码后,重新运行build_deploy.sh完成构建和部署。
  • 查看CloudWatch日志:验证是否出现hello, logs!,同时检查是否有反序列化相关的错误日志。
  • 测试API端点:使用curl调用API Gateway时,确保发送POST请求(你的配置中Method是POST),例如:
curl -X POST https://<你的API ID>.execute-api.<区域>.amazonaws.com/Prod/

内容的提问来源于stack exchange,提问作者Alex R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 13:57:39