Skip to content

_validate_request should raise ValidationError #263

@felixhummel

Description

@felixhummel

_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)

Footnotes

  1. usually in another layer, here in-view for brevity

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions