add_exception_handler
have type annotation problems
#2391
-
Since starlette 0.31.0 with mypy 0.108.0: from starlette.applications import Request, Starlette
from starlette.responses import JSONResponse
class MyException(Exception):
def __init__(self, message: str) -> None:
self.message = message
self.extra = "extra"
def my_exception_handler(request: Request, exc: MyException) -> JSONResponse:
return JSONResponse({"detail": exc.message, "extra": exc.extra}, status_code=400)
app = Starlette(debug=True, routes=[])
app.add_exception_handler(MyException, my_exception_handler) mypy produce:
And it definetly right, if handler must receive def my_exception_handler(request: Request, exc: Exception) -> JSONResponse: mypy produce:
And it is reasonable too, because I saw the problem, because fastapi bumped starlette version above 0.30.0. Anyway, it looks like a starlette issue. Because if I bind handler to handle some kind of exception, then I expect exact this exception or its subclass as a handler argument. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 9 replies
-
This part of the API can’t be typed correctly. Maybe something like #2042 (comment) works for you? |
Beta Was this translation helpful? Give feedback.
Nevermind, this works: