tiangolo/fastapi

RequestValidationError is **not** a sub-class of Pydantic's ValidationError

Kludex opened this issue ยท 5 comments

Discussed in #10421

Originally posted by valentinoli October 10, 2023

First Check

  • I added a very descriptive title here.
  • I used the GitHub search to find a similar question and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options ๐Ÿ‘†

Example Code

@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
    return PlainTextResponse(
        str(exc), status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
    )

Description

I was trying to handle both RequestValidationError and ValidationError by writing a custom handler for ValidationError but that doesn't work.

The docs state that

RequestValidationError is a sub-class of Pydantic's ValidationError

However, looking at FastAPI source code reveals that this is not the case.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.101.0

Pydantic Version

2.1.1

Python Version

3.11.3

Additional Context

No response

Should we fix the docs or the code? IMO having Pydantic's error makes more sense.

Documentation. But I'm just bringing it to @tiangolo 's attention.

hey Please choose this format

Here is main.py

from app.infrastructure.exception import validation_exception_handler

app = FastAPI(
    title=settings.PROJECT_NAME,
    openapi_url=f"{settings.API_V1_STR}openapi.json"
)

@app.exception_handler(RequestValidationError)
async def custom_validation_exception_handler(request, exc):
    return await validation_exception_handler(request, exc)

Here is exception.py

from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import Request

async def validation_exception_handler(request: Request, exc: RequestValidationError):
    error_messages = []
    for error in exc.errors():
        if error["type"] == "value_error.email":
            error_messages.append({"status_code": 422, "detail": "Invalid email address"})
        else:
            error_messages.append({"status_code": 422, "detail": error["msg"]})
    print(error_messages[0])
    return JSONResponse(
        status_code=422,
        content=error_messages[0],
    )

Here is my design pattern publically available
https://github.com/FaizanMunsaf/FastApi-MVC

+1 here;

The example code has become totally wrong since the str(exc) doesn't return the human readable version of the error(s).

It would be nice if the RequestValidationError could output the same text as ValidationError regardless of the inheritance.

This PR ( #11176 ) seems to fix it.