-
Notifications
You must be signed in to change notification settings - Fork 359
/
Copy pathmain.rs
100 lines (88 loc) · 2.9 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/// See https://github.com/awslabs/aws-lambda-rust-runtime for more info on Rust runtime for AWS Lambda
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent};
use serde::{Deserialize, Serialize};
use aws_lambda_json_impl::json;
use std::fs::File;
/// A simple Lambda request structure with just one field
/// that tells the Lambda what is expected of it.
#[derive(Deserialize)]
struct Request {
event_type: EventType,
}
/// Event types that tell our Lambda what to do do.
#[derive(Deserialize, Eq, PartialEq)]
enum EventType {
Response,
ExternalError,
SimpleError,
CustomError,
Panic,
}
/// A simple Lambda response structure.
#[derive(Serialize)]
struct Response {
req_id: String,
msg: String,
}
#[derive(Debug, Serialize)]
struct CustomError {
is_authenticated: bool,
req_id: String,
msg: String,
}
impl std::error::Error for CustomError {
// this implementation required `Debug` and `Display` traits
}
impl std::fmt::Display for CustomError {
/// Display the error struct as a JSON string
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let err_as_json = json!(self).to_string();
write!(f, "{}", err_as_json)
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
// required to enable CloudWatch error logging by the runtime
tracing::init_default_subscriber();
// call the actual handler of the request
let func = service_fn(func);
lambda_runtime::run(func).await?;
Ok(())
}
/// The actual handler of the Lambda request.
pub(crate) async fn func(event: LambdaEvent<Request>) -> Result<Response, Error> {
let (event, ctx) = event.into_parts();
// check what action was requested
match event.event_type {
EventType::SimpleError => {
// generate a simple text message error using `simple_error` crate
return Err(Box::new(simple_error::SimpleError::new("A simple error as requested!")));
}
EventType::CustomError => {
// generate a custom error using our own structure
let cust_err = CustomError {
is_authenticated: ctx.identity.is_some(),
req_id: ctx.request_id,
msg: "A custom error as requested!".into(),
};
return Err(Box::new(cust_err));
}
EventType::ExternalError => {
// try to open a non-existent file to get an error and propagate it with `?`
let _file = File::open("non-existent-file.txt")?;
// it should never execute past the above line
unreachable!();
}
EventType::Panic => {
panic!();
}
EventType::Response => {
// generate and return an OK response in JSON format
let resp = Response {
req_id: ctx.request_id,
msg: "OK".into(),
};
return Ok(resp);
}
}
}