_validate_request should not run abort(), but raise a ValidationError in order to better support centralized error handling.
Background
We use Pydantic models extensively, both in requests handled by flask-openapi
def using_request_body(body: MyPydanticModel):
pass
... as well as manually 1
def plain_model_validate():
...
MyPydanticModel.model_validate(request.json)
The Problem
The problem occurs when we try to handle ValidationErrors centrally using @errorhandler like so
@a.errorhandler(ValidationError)
def handle_validation_error(e):
content = validation_error_to_json(e)
response = make_response(content, 400)
response.content_type = 'application/json'
return response
This works for plain_model_validate, but not for using_request_body, because of the aforementioned call to abort() raises an HTTPException instead of a ValidationError.
Workaround
We currently work around this by raising in the validation_error_callback (before abort() is called) like so:
def _re_raise(e: Exception):
raise e
app = OpenAPI(..., validation_error_callback=_re_raise)
_validate_request should not run
abort(), but raise aValidationErrorin order to better support centralized error handling.Background
We use Pydantic models extensively, both in requests handled by flask-openapi
... as well as manually 1
The Problem
The problem occurs when we try to handle
ValidationErrors centrally using @errorhandler like soThis works for
plain_model_validate, but not forusing_request_body, because of the aforementioned call toabort()raises an HTTPException instead of aValidationError.Workaround
We currently work around this by raising in the
validation_error_callback(beforeabort()is called) like so:Footnotes
usually in another layer, here in-view for brevity ↩