Custom event_handler exceptions #2221
-
Hey I want to create a custom exception class when using the APIGatewayRestResolver event_handler, is this available ? I'll describe my use case: Best, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hi @royassis! Thanks for starting this thread. The short answer is yes, you can do that by extending the Using the ServiceError class. from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.exceptions import (
ServiceError,
)
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
app = APIGatewayRestResolver()
@app.get(rule="/already-running-route")
def conflict_error():
raise ServiceError(409, "CONFLICT -> Already running")
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) Creating your own exception class from http import HTTPStatus
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.exceptions import (
ServiceError,
)
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
app = APIGatewayRestResolver()
class ConflictError(ServiceError):
"""HTTP 409 conflict error class"""
def __init__(self, message: str):
super().__init__(HTTPStatus.CONFLICT, message)
@app.get(rule="/already-running-route")
def conflict_error():
raise ConflictError("CONFLICT -> Already running")
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) The result for both examples is I used Please let me know if you still have any questions about this and I can help you. |
Beta Was this translation helpful? Give feedback.
Hi @royassis! Thanks for starting this thread.
The short answer is yes, you can do that by extending the
ServiceError
class and creating your own exception class, but you don't have to. You already can do this by raising an exception using theServiceError
class and informing the HTTP status code and message you want. Let me give you an example of both situations:Using the ServiceError class.