ChatCrawlersearch across public Telegram Open the app
P

Python 中文交流群

snapshot for April 2025
April 2025 ×
27 April 2025
D
有大佬吗,fastapi的中间件里,怎么抛出原始的自定义异常,然后被捕获 (除开中间件里再写一次try excep)
只不过你super了HTTPException
I
你是希望捕获到401然后response返回吗
I
如果是继承HTTPException,你就试试不要添加异常处理器
不能被自定义异常捕获器捕获,会被最基础的Exception异常捕获到
D
Фотография
click to show
D
路由处理函数抛出自定义异常,是可以被正常捕获的, 但是中间件抛出的自定义异常却不行
from fastapi import FastAPI, Request, HTTPException from fastapi.responses import JSONResponse from starlette.middleware.base import BaseHTTPMiddleware app = FastAPI() class UnauthorizedException(HTTPException): def __init__(self, detail: str = "未授权的访问"): super().__init__(status_code=401, detail=detail) async def unauthorized_exception_handler(request: Request, exc: UnauthorizedException): return JSONResponse( status_code=exc.status_code, content={"code": exc.status_code, "message": exc.detail} ) # 添加异常处理器 app.add_exception_handler(UnauthorizedException, unauthorized_exception_handler) class AuthMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) async def dispatch(self, request: Request, call_next): # 检查认证(这里可以换成你的逻辑) token = request.headers.get("Authorization") if not token: # 这里改成直接返回Response,避免raise return JSONResponse( status_code=401, content={"code": 401, "message": "缺少认证令牌"} ) response = await call_next(request) return response # 添加中间件 app.add_middleware(AuthMiddleware) @app.get("/protected") async def protected_route(): return {"message": "这是一个受保护的路由"}
D
继承BaseHTTPMiddleware定义中间件,和使用函数式中间件,都一样报500
问了好几个ai,都说是异常捕获器注册顺序的问题,改半天也是不行
那就是只能在中间件里自己try excep了
Фотография
click to show
那这是最简单,日志最少的了
D
中间件自己捕获
Open in Telegram Каталог площадок Искать в ChatCrawler

A snapshot of an open public feed from the search index ChatCrawler — “Google for public Telegram”; refreshed as the venue is crawled. Times are UTC.

Public content only, official Telegram API. About · FAQ · What we do not do · Remove a page · Catalog