How to deal with this Pylance type error regarding the exception handler? #2371
Replies: 3 comments
-
I've got it. The type annotation for the second parameter of async def handle_error(request: Request, exc: Exception) -> JSONResponse:
return JSONResponse({"info": str(exc)}, status_code=500) But I want to annotate the second parameter of |
Beta Was this translation helpful? Give feedback.
-
This piece of code utilizes assert to change the type of the variable from typing import Annotated
import uvicorn
from pydantic import BaseModel, StringConstraints, ValidationError
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse
from starlette.routing import Route
class DirectJsonResponse(JSONResponse):
def render(self, content: bytes) -> bytes:
return content
Name = Annotated[str, StringConstraints(min_length=3, max_length=12)]
class Info(BaseModel):
name: Name
async def hello(request: Request):
req_body = Info.model_validate(await request.json())
return PlainTextResponse(f"Hello, {req_body.name}!")
async def validation_error_handler(request: Request, exc: Exception) -> JSONResponse:
assert type(exc) == ValidationError # use assert to change type of `exc`
return DirectJsonResponse(exc.json().encode(), status_code=400)
exception_handlers = {
ValidationError: validation_error_handler,
}
routes = [
Route("/", hello, methods=["POST"]),
]
app = Starlette(
debug=True,
routes=routes,
exception_handlers=exception_handlers,
)
if __name__ == "__main__":
uvicorn.run("main:app", reload=True) |
Beta Was this translation helpful? Give feedback.
-
After the automatic update of the Python plugin in VSCode, it no longer throws errors. |
Beta Was this translation helpful? Give feedback.
-
My code is as follows:
Pylance is throwing an error on line 31. The error message is as follows:
At present, the functionality of the exception handler is normal; the test content is as follows:
Beta Was this translation helpful? Give feedback.
All reactions