Skip to content

Commit c4594f7

Browse files
authored
doc: Add an example for using the anyhow crate (#904)
* Add "error handling with anyhow" example Signed-off-by: Taiki Ono <[email protected]> * More doc for users who use external error types Signed-off-by: Taiki Ono <[email protected]> --------- Signed-off-by: Taiki Ono <[email protected]>
1 parent 9b88cea commit c4594f7

File tree

5 files changed

+48
-0
lines changed

5 files changed

+48
-0
lines changed
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/target
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "basic-error-anyhow"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
anyhow = "1"
8+
lambda_runtime = { path = "../../lambda-runtime" }
9+
serde = "1"
10+
tokio = { version = "1", features = ["macros"] }

examples/basic-error-anyhow/README.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# AWS Lambda Function Error Handling With `anyhow` Crate Example
2+
3+
This example shows how to use external error types like `anyhow::Error`.
4+
5+
## Build & Deploy
6+
7+
1. Install [cargo-lambda](https://github.com/cargo-lambda/cargo-lambda#installation)
8+
2. Build the function with `cargo lambda build --release`
9+
3. Deploy the function to AWS Lambda with `cargo lambda deploy --iam-role YOUR_ROLE`
10+
11+
## Build for ARM 64
12+
13+
Build the function with `cargo lambda build --release --arm64`
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
use anyhow::bail;
2+
use lambda_runtime::{service_fn, Error, LambdaEvent};
3+
use serde::Deserialize;
4+
5+
#[derive(Deserialize)]
6+
struct Request {}
7+
8+
/// Return anyhow::Result in the main body for the Lambda function.
9+
async fn function_handler(_event: LambdaEvent<Request>) -> anyhow::Result<()> {
10+
bail!("This is an error message");
11+
}
12+
13+
#[tokio::main]
14+
async fn main() -> Result<(), Error> {
15+
lambda_runtime::run(service_fn(|event: LambdaEvent<Request>| async move {
16+
function_handler(event)
17+
.await
18+
.map_err(Into::<Box<dyn std::error::Error>>::into)
19+
}))
20+
.await
21+
}

lambda-runtime/src/diagnostic.rs

+3
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ use crate::{deserializer::DeserializeError, Error};
77
///
88
/// `Diagnostic` is automatically derived for some common types,
99
/// like boxed types that implement [`Error`][std::error::Error].
10+
/// If you use an error type which comes from a external crate like anyhow,
11+
/// you need convert it to common types like `Box<dyn std::error::Error>`.
12+
/// See the examples for more details.
1013
///
1114
/// [`error_type`][`Diagnostic::error_type`] is derived from the type name of
1215
/// the original error with [`std::any::type_name`] as a fallback, which may

0 commit comments

Comments
 (0)