[BUG] Overwriting HTTPException and RequestValidationError does not work via FastAPI exceptions handlers init
See original GitHub issueWhen initilizing FastAPI, an exception_handlers dictionary can be passed, mapping Exceptions/Error Codes to callables. When using this method to set the exception handlers, the HTTPException and RequestValidationError can not be overwritten.
Code to Reproducte
import logging
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
from fastapi.exception_handlers import request_validation_exception_handler
logger = logging.getLogger(__name__)
# app = FastAPI()
# @app.exception_handler(RequestValidationError)
async def my_request_validation_exception_handler(
req: Request, exc: RequestValidationError
):
logger.info("my_request_validation_exception_handler")
return await request_validation_exception_handler(req, exc)
app = FastAPI(exception_handlers={RequestValidationError: my_request_validation_exception_handler})
@app.get("/test")
def test(param: int):
return JSONResponse(
status_code=200,
content={"message": "successful test with param {}".format(param)},
)
if __name__ == "__main__":
uvicorn.run("api:app", host="localhost", port=2000, reload=True)
Now a curl "http://localhost:2000/test"
will not show the logger.info("my_request_validation_exception_handler")
log statement. However, when using the commented out code it works fine. I want to use the other way to keep the handlers in a separate file.
Environment
- OS: Windows/WSL
- FastAPI Version: 0.54.2
- Python version: 3.6.9
Origin
As far as i can see this is coming from the setup method
self.add_exception_handler(HTTPException, http_exception_handler)
self.add_exception_handler(
RequestValidationError, request_validation_exception_handler
)
Starlette will overwrite the custom handlers in the add_exception_handler method
def add_exception_handler(
self,
exc_class_or_status_code: typing.Union[int, typing.Type[Exception]],
handler: typing.Callable,
) -> None:
self.exception_handlers[exc_class_or_status_code] = handler
self.middleware_stack = self.build_middleware_stack()
Would be great if setup() could first check whether a handler for this exception exists already.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:3
- Comments:14 (9 by maintainers)
Top Results From Across the Web
Handling Errors - FastAPI
These handlers are in charge of returning the default JSON responses when you raise an HTTPException and when the request has invalid data....
Read more >FastAPI - Pydantic - Value Error Raises Internal Server Error
If you're not raising an HTTPException then normally any other uncaught exception will generate a 500 response (an Internal Server Error ).
Read more >3 Ways to Handle Errors in FastAPI That You Need to Know
3 Ways to Handle Errors in FastAPI That You Need to Know · 1. HTTPException · 2. Create a Custom Exception · 3....
Read more >Fast API Tutorial, Part 19: Handling Errors - YouTube
When building an API you'll want to be able to manually handle errors. For example, if a user submits a GET request for...
Read more >Exceptions - Starlette
Starlette allows you to install custom exception handlers to deal with how you ... In particular you might want to override how the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thanks for all the discussion here everyone! ☕
@uriyyo fixed this in https://github.com/tiangolo/fastapi/pull/1924, available in FastAPI version
0.61.2
. 🎉Well, in the past when @tiangolo saw one first, he basically merged that one (if it was good) and the next was discharged. So I recommend you to mention #1887 on your solution and explain that you’ve implemented it without knowing that it was already implemented. Then you just wait. 😎 👍