0

I am not able to handle customized exception for request body, 422 exception is directly rasing from fastapi itself

I tried using:

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
    )

app.include_router(router)
app.add_exception_handler(RequestValidationError, validation_exception_handler)

But still Iam not able to handle customized exception

  • In addition to the link above, please have a look [here](https://stackoverflow.com/a/71800464/17865804) and [here](https://stackoverflow.com/a/72833284/17865804) as well – Chris Aug 18 '23 at 04:46

1 Answers1

0

There is an issue in your code where you are trying to use jsonable_encoder on the exc.errors() and exc.body objects. The exc.errors() method returns a list of error dictionaries, and the exc.body attribute is a dictionary containing the parsed request body.

Use JSONResponse() instead of json_decoder()

Ulugbek
  • 1
  • 2
  • When a validation error occurs while processing a request in FastAPI application, the custom exception handler I defined with @app.exception_handler(RequestValidationError) should be invoked automatically. Instead of that exception being raised and displayed directly in the Swagger UI – Vinuta Basavaraj Hiremath Aug 14 '23 at 13:02