sanic-org / sanic-ext

Extended Sanic functionality
https://sanic.dev/en/plugins/sanic-ext/getting-started.html
MIT License
50 stars 36 forks source link

[Bug] Json validator throws 500 instead of 400 #227

Open ameyarao98 opened 1 year ago

ameyarao98 commented 1 year ago

Describe the bug Json validator throws 500 instead of 400:

Error while handling error: 'NoneType' object has no attribute '__name__'
Stack: Traceback (most recent call last):
  File "/usr/local/lib/python3.11/site-packages/sanic_ext/extras/validation/validators.py", line 25, in validate_body
    return validator(model, body)
           ^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/sanic_ext/extras/validation/validators.py", line 35, in _validate_instance
    return model(**data)
           ^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/pydantic/main.py", line 165, in __init__
    __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)
pydantic_core._pydantic_core.ValidationError: 1 validation error for SiweMessageSchema
message
  Input should be a valid string [type=string_type, input_value=11, input_type=int]
    For further information visit https://errors.pydantic.dev/2.3/v/string_type

To Reproduce

class MessageSchema(BaseModel):
    message: str

@validate(json=MessageSchema)
async def verify(request: Request, body: SiweMessageSchema):

Send request to endpoint with non str message field

Expected behavior A 400 is thrown with the validation error. a 500 is thrown instead

Environment (please complete the following information):

python = "^3.11"
sanic = { extras = ["ext"], version = "^23.6.0" }
pydantic = "^2.2.0"

Additional context Seems like a property change in pydantic v2?

begoat commented 2 months ago

I copied implementations of validate_body and do_validation function and modified the exception handling in validate_body and it worked.

image