-
Notifications
You must be signed in to change notification settings - Fork 411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature request: add exception handlers return types to OpenAPI responses #4928
Comments
Thanks for opening your first issue here! We'll come back to you as soon as we can. |
Hi @ThomasLeedsLRH! Thanks for opening this issue and bringing this suggestion. I don't think we should include I will leave this issue open to hear more from you and other customers. |
Hi @leandrodamascena, The problem is that the "Validation Error" response is always included in the OpenAPI schema (primarily due to this code), which can lead to incorrect documentation generation when using In my case, I want to return validation errors with a {
"error": {
"statusCode": 400,
"message": "Invalid request parameters",
"description": {
"body.user_email": "Field required"
}
}
} To achieve this, I am using a custom exception handler and a custom class: def validation_error_description(exc: RequestValidationError):
"""
Extracts and formats validation error messages from a RequestValidationError.
It creates a dictionary where each key represents the location of the validation error
in the request (e.g., "body.email"), and the corresponding value is the error message.
Args:
exc (RequestValidationError): The exception raised during request validation.
Returns:
dict: A dictionary containing detailed descriptions of each validation error.
"""
error_description = {}
for error in exc.errors():
# Creating a string representation of the location (path) of each error in the request
field = ".".join([str(elem) for elem in error["loc"]])
# Mapping the error location to its message
error_description[field] = error["msg"]
return error_description
class ExceptionHandlers:
"""
A class to handle common exceptions for AWS Lambda functions using AWS Lambda Powertools.
Attributes:
app (LambdaPowertoolsApp): An instance of the LambdaPowertoolsApp.
logger (Logger): An instance of the Powertools Logger.
"""
def __init__(self, app, logger=None):
self.app = app
self.logger = logger or Logger()
# 400 Bad Request
def invalid_params(self, exc):
"""
Handles RequestValidationError exceptions
by logging the error and returning a custom Response.
Args:
exc (RequestValidationError): The exception object.
Returns:
Response: A custom response with a status code of 400, indicating a bad request.
"""
if exc.__class__.__name__ == "TypeError" and "JSON object must be" in str(exc):
error_description = {"body": "Invalid or empty request body"}
else:
if isinstance(exc, RequestValidationError):
error_description = validation_error_description(exc)
else:
error_description = str(exc)
self.logger.error(
f"Data validation error: {error_description}",
extra={
"path": self.app.current_event.path,
"query_strings": self.app.current_event.query_string_parameters,
},
)
return Response(
status_code=HTTPStatus.BAD_REQUEST.value,
content_type=content_types.APPLICATION_JSON,
body={
"error": {
"statusCode": HTTPStatus.BAD_REQUEST.value,
"message": "Invalid request parameters",
"description": error_description,
}
},
)
...
exception_handlers = ExceptionHandlers(app=app)
...
@app.exception_handler([RequestValidationError, ValidationError, ValidationException])
def handle_invalid_params_wrapper(exc):
return exception_handlers.invalid_params(exc) However, when I generate the OpenAPI schema, I have to manually add the @router.get(
"/user/<id>",
summary="Get user data",
responses={
200: {...},
400: {
"description": "Bad request",
"content": {"application/json": {"model": BadRequestResponse}},
},
... But I also end up with a Ideally, I would like to be able to reuse response models from At the very least, the |
Hi @Hatter1337! Sorry I completely missed this comment! I'm adding it to my backlog to respond to this week, okay? |
Sure, thank you |
Hi @leandrodamascena, sorry for chasing up but is there any update on this? |
Hi everyone! I'm adding this issue to investigate again in 3 weeks and have a final decision on how we can solve it! I was reading in detail and we have 2 situations here: 1 - Customers that don't want to return 422 by default when a response doesn't match the function return. 2 - The ability to automatically add exceptions in the OpenAPI schema. I did some testing and it's not a breaking change if we add this as a flag in the resolver. Thank you for your patience and I hope to have news soon. |
Use case
I use an API Gateway event handler with validation enabled and I'd like exception handlers response types to be automatically add to the openAPI schema. I can add
responses
parameter to my endpoint definition, however it's not ideal as it adds a lot off repetition, duplication and introduce potential for incorrect openAPI schemas.Solution/User Experience
This is what currently gets generated:
ideally this would be genrated:
This would require a status code to be attached to each
exception_handler
and potentially some other context.Alternative solutions
No response
Acknowledgment
The text was updated successfully, but these errors were encountered: