How to log more info on 422 unprocessable entity #6678
-
I get this a lot in development and can usually pretty quickly figure out what is wrong with my json payload. However, I'd love a way to see what exactly the validation error is when I get this error. Is there a way I can log what the specific schema validation error is on the server side? |
Beta Was this translation helpful? Give feedback.
Replies: 17 comments 1 reply
-
Just the other day I had a pretty absurd issue about exactly that My gui was doing a fetch request and thanks to the apple keyword crap, I set the content-type to The 422 error indicated that value wasn't a dict I spend too much time till I noticed the additional This would be avoided with better 422 error or a way to debug it |
Beta Was this translation helpful? Give feedback.
-
@nickgieschen catch exception def register_exception(app: FastAPI):
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
exc_str = f'{exc}'.replace('\n', ' ').replace(' ', ' ')
# or logger.error(f'{exc}')
logger.error(request, exc_str)
content = {'status_code': 10422, 'message': exc_str, 'data': None}
return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY) after you can log error and get response and you can see issue 394 @ruslankrivoshein |
Beta Was this translation helpful? Give feedback.
-
Thanks. Can you tell me what logger that is that you can pass request as the first argument? |
Beta Was this translation helpful? Give feedback.
-
def log_message(request: Request, e):
logger.error('start error'.center(60, '*'))
logger.error(f'{request.method} {request.url}')
logger.error(f'error is {e}')
logger.error('end error'.center(60, '*'))
log_message(request, exc_str) or logger.error(exc_str) |
Beta Was this translation helpful? Give feedback.
-
The above examples are excerpts of handling-errors documentation. import logging
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
exc_str = f'{exc}'.replace('\n', ' ').replace(' ', ' ')
logging.error(f"{request}: {exc_str}")
content = {'status_code': 10422, 'message': exc_str, 'data': None}
return JSONResponse(content=content, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY) This will produce something along the lines of:
This error is not only bound to the header, but also if the data submitted does not match the |
Beta Was this translation helpful? Give feedback.
-
presume it should be |
Beta Was this translation helpful? Give feedback.
-
What is the significance of |
Beta Was this translation helpful? Give feedback.
-
This should be the standard implementation IMHO... a beginner like me had to do quite a lot of digging simply because the error wasn't expressive enough :P |
Beta Was this translation helpful? Give feedback.
-
wouldn't this catch all errors instead of only 422? and what about the 10422 like @dancaugherty mentioned? |
Beta Was this translation helpful? Give feedback.
-
At least if |
Beta Was this translation helpful? Give feedback.
-
yeah i agree, especially because there's no real way to log it properly if you'll get a 422 |
Beta Was this translation helpful? Give feedback.
-
or it would be cool to define when creating the pydantic model...
|
Beta Was this translation helpful? Give feedback.
-
@nickgieschen @Torxed @zwessels @dancaugherty @VBoB13 @JustinGuese please see codes
|
Beta Was this translation helpful? Give feedback.
-
I see alot of answers here, which one is best for simply returning the field error to the user? Such as: "field" : pause is missing: ? Here is my code:
The problem is, that as soon as the scheme is not correct, i can not get further than line one, which means i can not use the RequestValidationError ? |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help here everyone! 👏 🙇 If that solves the original problem, then you can close this issue @nickgieschen ✔️
|
Beta Was this translation helpful? Give feedback.
-
@tiangolo can we add a logger in the exception handlers
so that I see on my terminal this
will be happy to open a PR on this |
Beta Was this translation helpful? Give feedback.
-
For future travelers here's the section in the docs that covers this topic: https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body |
Beta Was this translation helpful? Give feedback.
The above examples are excerpts of handling-errors documentation.
For the sake of clarity to anyone ending up here after having the same issues as OP, here's the full code @panla scissored in: