question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] how to return exception from validator schema?

See original GitHub issue

i have schema with validator

@validator('number')
    def validate_phone(cls, v):
        if not validate_mobile_number(v):
            return {'msg': 'incorrect mobile number'}
        return v

when i send query with correct or incorrect number, i give response like:

{
  "detail": [
    {
      "loc": [
        "body",
        "user",
        "number"
      ],
      "msg": "expected string or bytes-like object",
      "type": "type_error"
    }
  ]
}

but where is my exception?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:9 (5 by maintainers)

github_iconTop GitHub Comments

4reactions
prostomarkeloffcommented, Nov 9, 2019

@foozzi For example:

from fastapi import FastAPI
import pydantic

app = FastAPI()


class BadIdError(pydantic.PydanticValueError):
    msg_template = "You sent a wrong id!"


class MyUser(pydantic.BaseModel):
    id: int
    name: str

    @pydantic.validator("id")
    def validate_id(cls, v):
        if v + 1 != 10:
            raise BadIdError()
        return v


@app.post("/create")
async def create_user(_: MyUser):
    return {"status": "ok"}

image

2reactions
dmontagucommented, Nov 7, 2019

@foozzi

You aren’t using a pydantic.validator properly – you need to raise an error to cause a ValidationError, not return a dict. You probably don’t need to set pre=True or always=True if you are just trying to validate if a string is a valid phone number, but you should only ever return a value that passes your validation. If the input fails validation, you need to raise an error.

If you are trying to get a custom error message, you may need to subclass pydantic.errors.PydanticValueError, for example, like this (taken out of pydantic.errors):

class StrictBoolError(PydanticValueError):
    msg_template = 'value is not a valid boolean'

and then raise that error in your validator.

You should probably also read the pydantic validator docs to make sure you understand what is going on.

If you are trying to change the You have to raise a ValueError, TypeError, or AssertionError inside a validator in order to get an error output. You can read the pydantic docs about validators for more details.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Handling Validation Errors - python-jsonschema
When an invalid instance is encountered, a ValidationError will be raised or returned, depending on which method or function is used. exception jsonschema....
Read more >
How to return all errors of a schema using RestAssured
I am trying to validate a schema using RestAssured. I have a response { "a" : 1, "b" : 1, "c" : 1...
Read more >
how to catch excpetion from schema validation
I am using Message filter in which I am doing schema validation and returning to subflow whenever validation fails and I am setting...
Read more >
Queue Schema Validation Does Not Return Helpful Exception ...
Workaround 3 (Rely on sanity checks): Not as good as using the schema validation depending on the sanity checks and all validations would...
Read more >
What is .Net Core Web Api Model Validation error response ...
2 Answers · Create custom IActionResult. By default, when display the validation error, it will return BadRequestObjectResult and the HTTP status ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found