question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Raise exception in python-fastApi middleware

See original GitHub issue

I am trying to validate token in fastapi middleware but this seems impossible. As i am thinking middleware needs to make next call although its not required. I am not able to find any good solution to handle token in one go in this python-fastapi backend. Any help is appreciated.

@app.middleware("http")
async def add_middleware_here(request: Request, call_next):
    token = request.headers["Authorization"]
    try:
        verification_of_token = verify_token(token)
        if verification_of_token:
            response = await call_next(request)
            return response
    except InvalidSignatureError as er:
        raise HTTPException(status_code=401)

My expectation is that it should throw 401 error once wrong token is provided. Instead it throws 500 with below Exception traceback:

Traceback (most recent call last):
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 385, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\fastapi\applications.py", line 140, in __call__
    await super().__call__(scope, receive, send)
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\starlette\applications.py", line 134, in __call__
    await self.error_middleware(scope, receive, send)
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\starlette\middleware\errors.py", line 178, in __call__
    raise exc from None
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\starlette\middleware\errors.py", line 156, in __call__
    await self.app(scope, receive, _send)
  File "c:\users\covered\appdata\local\programs\python\python38\lib\site-packages\starlette\middleware\base.py", line 26, in __call__
    await response(scope, receive, send)
TypeError: 'NoneType' object is not callable

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:12 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
chris-allnuttcommented, Apr 24, 2020

the comment in there has the solution tho return Response(content="", status_code=401)

but I agree this is unclear would be good to know if this should be in the documentation or if it’s a bug @tiangolo and others think should be addressed. Something like bubbling up if the caught below exception is already of type HTTPException.

1reaction
vancouverwillcommented, Apr 22, 2020

hey @priyankagupta34 I just came across the same issue, seems weirdly HTTPException doesn’t work in middle ware. See https://github.com/tiangolo/fastapi/issues/1125

Read more comments on GitHub >

github_iconTop Results From Across the Web

Raise exception in python-fastApi middleware - Stack Overflow
You need to return a response. I'll show you how you can make it work: from fastapi.responses import JSONResponse @app.middleware("http") ...
Read more >
Handling Errors - FastAPI
When a request contains invalid data, FastAPI internally raises a RequestValidationError . And it also includes a default exception handler for it. To...
Read more >
tiangolo/fastapi - Gitter
I think starlette's ServerErrorMiddleware is supposed to be used for that, ... handling "Exception" I think I should catch all unmanaged exceptions.
Read more >
fastapi-rfc7807 - PyPI
FastAPI middleware which translates server-side exceptions into RFC-7807 compliant problem detail error responses. Installation. fastapi_rfc7807 requires Python ...
Read more >
Integrate Sentry to FastAPI - Phil Girard - Medium
All the exceptions that can happen during a request are catch in a general handler · A sentry context is created with additional...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found