Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: ASGIApp's with custom exception handlers result in Litestar throwing AttributeError when an exception occurs within the ASGI APP #3934

Closed
1 of 4 tasks
Skelmis opened this issue Jan 9, 2025 · 3 comments · Fixed by #3945
Labels
area/exceptions area/middleware This PR involves changes to the middleware Bug 🐛 This is something that is not working as expected

Comments

@Skelmis
Copy link

Skelmis commented Jan 9, 2025

Description

If an ASGI App mounted using @asgi("/", is_mount=True) defines a custom exception handler, litestar will throw an AttributeError from the litestar/middleware/_internal/exceptions/middleware.py file when said ASGI App raises an exception.

It looks like the file takes app: ASGIApp but the middleware exception handling attempts to possibly treat it like app: Litestar. One way I have found which resolves this (and possibly introduces unintended side effects) is as follows:

...

litestar_app = scope["app"]
from litestar import Litestar
if not isinstance(litestar_app, Litestar):
    # Unknown ASGI App, cannot handle automatically
    raise

if litestar_app.logging_config and (logger := litestar_app.logger):
    self.handle_exception_logging(logger=logger, logging_config=litestar_app.logging_config, scope=scope)

...

URL to code causing the issue

No response

MCVE

from litestar import Litestar, asgi
from litestar.types import Receive, Scope, Send
from starlette.exceptions import HTTPException
from fastapi import FastAPI

async def log_error(_, exc: HTTPException):
    raise exc

@asgi("/", is_mount=True)
async def admin(scope: Scope, receive: Receive, send: Send) -> None:
    app = FastAPI(exception_handlers={500: log_error})
    @app.get("/")
    async def route() -> None:
        raise Exception("sub app")
    await app(scope, receive, send)

app = Litestar(route_handlers=[admin])

Steps to reproduce

1. Run the MCVE
2. Navigate to the site and observe the `AttributeError` being thrown by Litestar

Screenshots

No response

Logs

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/skelmis/.cache/pypoetry/virtualenvs/zero_website-Nzy3tQZa-py3.11/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 403, in run_asgi
    result = await app(  # type: ignore[func-returns-value]
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/skelmis/.cache/pypoetry/virtualenvs/zero_website-Nzy3tQZa-py3.11/lib/python3.11/site-packages/uvicorn/middleware/proxy_headers.py", line 60, in __call__
    return await self.app(scope, receive, send)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/skelmis/.cache/pypoetry/virtualenvs/zero_website-Nzy3tQZa-py3.11/lib/python3.11/site-packages/litestar/app.py", line 615, in __call__
    await self.asgi_handler(scope, receive, self._wrap_send(send=send, scope=scope))  # type: ignore[arg-type]
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/skelmis/.cache/pypoetry/virtualenvs/zero_website-Nzy3tQZa-py3.11/lib/python3.11/site-packages/litestar/middleware/_internal/exceptions/middleware.py", line 166, in __call__
    if litestar_app.logging_config and (logger := litestar_app.logger):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'FastAPI' object has no attribute 'logging_config'

Litestar Version

poetry show litestar
 name         : litestar                                                                        
 version      : 2.14.0

Platform

  • Linux
  • Mac
  • Windows
  • Other (Please specify in the description above)
@Skelmis Skelmis added the Bug 🐛 This is something that is not working as expected label Jan 9, 2025
@Alc-Alc Alc-Alc added area/middleware This PR involves changes to the middleware area/exceptions labels Jan 9, 2025
@provinzkraut
Copy link
Member

I'm a bit on the fence whether or not this is a bug. The issue here come from the fact that both Litestar and FastAPI store themselves in scope["app"], and assume they can always be retrieved that way, which, as this issue shows, is not true.

However, as a general rule, ASGI applications modifying the scope should be expected, and e.g. passing scope.copy() to the FastAPI application solves this issue.

We should probably add a warning about this in our docs and mention how to handle it correctly, maybe even issue a warning that the mounted application modified the scope.

@provinzkraut
Copy link
Member

I've created #3945 nevertheless, which should help to solve this and similar issues

Copy link

This issue has been closed in #3945. The change will be included in upcoming releases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/exceptions area/middleware This PR involves changes to the middleware Bug 🐛 This is something that is not working as expected
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants