11// This example requires the following input to succeed:
22// { "command": "do something" }
33
4- use lambda_runtime:: { service_fn, tracing, Error , LambdaEvent } ;
4+ use lambda_runtime:: { service_fn, tracing, Diagnostic , Error , LambdaEvent } ;
55use serde:: { Deserialize , Serialize } ;
66
7- /// This is also a made-up example. Requests come into the runtime as unicode
8- /// strings in json format, which can map to any structure that implements `serde::Deserialize`
9- /// The runtime pays no attention to the contents of the request payload.
107#[ derive( Deserialize ) ]
118struct Request {
129 command : String ,
1310}
1411
15- /// This is a made-up example of what a response structure may look like.
16- /// There is no restriction on what it can be. The runtime requires responses
17- /// to be serialized into json. The runtime pays no attention
18- /// to the contents of the response payload.
1912#[ derive( Serialize ) ]
2013struct Response {
2114 req_id : String ,
2215 msg : String ,
2316}
2417
18+ #[ derive( Debug ) ]
19+ struct HandlerError ( String ) ;
20+
21+ impl std:: fmt:: Display for HandlerError {
22+ fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
23+ write ! ( f, "{}" , self . 0 )
24+ }
25+ }
26+
27+ impl From < HandlerError > for Diagnostic {
28+ fn from ( e : HandlerError ) -> Diagnostic {
29+ Diagnostic {
30+ error_type : "HandlerError" . into ( ) ,
31+ error_message : e. 0 ,
32+ }
33+ }
34+ }
35+
2536#[ tokio:: main]
2637async fn main ( ) -> Result < ( ) , Error > {
2738 // required to enable CloudWatch error logging by the runtime
@@ -38,17 +49,18 @@ async fn main() -> Result<(), Error> {
3849 Ok ( ( ) )
3950}
4051
41- pub ( crate ) async fn my_handler ( event : LambdaEvent < Request > ) -> Result < Response , Error > {
42- // extract some useful info from the request
52+ pub ( crate ) async fn my_handler ( event : LambdaEvent < Request > ) -> Result < Response , HandlerError > {
4353 let command = event. payload . command ;
4454
45- // prepare the response
55+ if command == "fail" {
56+ return Err ( HandlerError ( "simulated handler error" . into ( ) ) ) ;
57+ }
58+
4659 let resp = Response {
4760 req_id : event. context . request_id ,
4861 msg : format ! ( "Command {command} executed." ) ,
4962 } ;
5063
51- // return `Response` (it will be serialized to JSON automatically by the runtime)
5264 Ok ( resp)
5365}
5466
0 commit comments