@@ -487,9 +487,10 @@ You can use **`not_found`** decorator to override this behaviour, and return a c
487
487
488
488
=== "app.py"
489
489
490
- ```python hl_lines="10 12 15 " title="Handling not found"
490
+ ```python hl_lines="11 13 16 " title="Handling not found"
491
491
from aws_lambda_powertools import Logger, Tracer
492
492
from aws_lambda_powertools.logging import correlation_paths
493
+ from aws_lambda_powertools.event_handler import content_types
493
494
from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver, Response
494
495
from aws_lambda_powertools.event_handler.exceptions import NotFoundError
495
496
@@ -514,7 +515,6 @@ You can use **`not_found`** decorator to override this behaviour, and return a c
514
515
def catch_me_if_you_can():
515
516
return {"message": "oh hey"}
516
517
517
- # You can continue to use other utilities just as before
518
518
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
519
519
@tracer.capture_lambda_handler
520
520
def lambda_handler(event, context):
@@ -524,6 +524,47 @@ You can use **`not_found`** decorator to override this behaviour, and return a c
524
524
525
525
### Exception handling
526
526
527
+ You might want to handle an exception outside your route like custom validation errors or anything that warrants a different response (status code, headers, body).
528
+
529
+ You can use ` exception_handler ` decorator with any Python exception.
530
+
531
+ === "app.py"
532
+
533
+ ```python hl_lines="10 15" title="Exception handling"
534
+ from aws_lambda_powertools import Logger, Tracer
535
+ from aws_lambda_powertools.logging import correlation_paths
536
+ from aws_lambda_powertools.event_handler import content_types
537
+ from aws_lambda_powertools.event_handler.api_gateway import ApiGatewayResolver, Response
538
+
539
+ tracer = Tracer()
540
+ logger = Logger()
541
+ app = ApiGatewayResolver()
542
+
543
+ @app.exception_handler(ValueError)
544
+ def handle_value_error(ex: ValueError):
545
+ metadata = {"path": app.current_event.path}
546
+ logger.error(f"Malformed request: {ex}", extra=metadata)
547
+
548
+ return Response(
549
+ status_code=400,
550
+ content_type=content_types.TEXT_PLAIN,
551
+ body="Invalid request",
552
+ )
553
+
554
+
555
+ @app.get("/hello")
556
+ @tracer.capture_method
557
+ def hello_name():
558
+ name = app.current_event.get_query_string_value(name="name")
559
+ if name is not None:
560
+ raise ValueError("name query string must be present")
561
+ return {"message": f"hello {name}"}
562
+
563
+ @logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
564
+ @tracer.capture_lambda_handler
565
+ def lambda_handler(event, context):
566
+ return app.resolve(event, context)
567
+ ```
527
568
528
569
529
570
### Raising HTTP errors
0 commit comments