encode / starlette

The little ASGI framework that shines. 🌟
https://www.starlette.io/
BSD 3-Clause "New" or "Revised" License
10.28k stars 939 forks source link

when use BaseHTTPMiddleware can't catch BackgroundTasks exceptions #2658

Closed YuQibing closed 3 months ago

YuQibing commented 3 months ago

The starting point for issues should usually be a discussion...

https://github.com/encode/starlette/discussions

when i add LoggingMiddleware, if i add_task but miss name args, can't catch exception if i comment add_middleware ,can get exception


from fastapi import FastAPI, Request, BackgroundTasks, HTTPException
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.middleware.exceptions import ExceptionMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.errors import ServerErrorMiddleware

async def generic_exception_handler(request: Request, exc: Exception):
    print("!!!exception")
    return JSONResponse(
        status_code=500,
        content={"message": "aaaa"},
    )

class LoggingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        print(f"Request URL: {request.url}")
        response = await call_next(request)
        print(f"Response Status: {response.status_code}")
        return response

app = FastAPI()

app.add_middleware(LoggingMiddleware)

app.add_exception_handler(Exception, generic_exception_handler)

async def background_task(name: str):
    1/0

@app.get("/")
async def run_background_task(background_tasks: BackgroundTasks):
    background_tasks.add_task(background_task)
    return {"message": "Background task started"}

when i add LoggingMiddleware, if i add_task but miss name args, can't catch exception if i comment add_middleware ,can get exception can u help me..

[!IMPORTANT]

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar