处理请求并捕获错误
(self, request: Request, call_next: Callable)
| 25 | self.debug = debug |
| 26 | |
| 27 | async def dispatch(self, request: Request, call_next: Callable) -> Response: |
| 28 | """处理请求并捕获错误""" |
| 29 | try: |
| 30 | return await call_next(request) |
| 31 | |
| 32 | except EmotionalChatException as e: |
| 33 | # 处理自定义异常 |
| 34 | logger.error(f"自定义异常: {e.error_code} - {e.message}", extra={ |
| 35 | "error_code": e.error_code, |
| 36 | "details": e.details, |
| 37 | "path": str(request.url), |
| 38 | "method": request.method |
| 39 | }) |
| 40 | |
| 41 | # 查找对应的处理器 |
| 42 | handler = EXCEPTION_HANDLERS.get(type(e)) |
| 43 | if handler: |
| 44 | status_code, error_data = handler(e) |
| 45 | else: |
| 46 | status_code, error_data = 500, {"error": "系统错误", "details": str(e)} |
| 47 | |
| 48 | return JSONResponse( |
| 49 | status_code=status_code, |
| 50 | content=format_error( |
| 51 | error=e, |
| 52 | error_code=e.error_code, |
| 53 | status_code=status_code, |
| 54 | details=e.details |
| 55 | ) |
| 56 | ) |
| 57 | |
| 58 | except HTTPException as e: |
| 59 | # 处理FastAPI HTTP异常 |
| 60 | logger.warning(f"HTTP异常: {e.status_code} - {e.detail}", extra={ |
| 61 | "status_code": e.status_code, |
| 62 | "path": str(request.url), |
| 63 | "method": request.method |
| 64 | }) |
| 65 | |
| 66 | return JSONResponse( |
| 67 | status_code=e.status_code, |
| 68 | content=format_error( |
| 69 | error=e.detail, |
| 70 | error_code="HTTP_EXCEPTION", |
| 71 | status_code=e.status_code |
| 72 | ) |
| 73 | ) |
| 74 | |
| 75 | except Exception as e: |
| 76 | # 处理未预期的异常 |
| 77 | logger.error(f"未预期异常: {type(e).__name__} - {str(e)}", extra={ |
| 78 | "exception_type": type(e).__name__, |
| 79 | "path": str(request.url), |
| 80 | "method": request.method, |
| 81 | "traceback": traceback.format_exc() |
| 82 | }) |
| 83 | |
| 84 | error_message = str(e) if self.debug else "服务器内部错误" |
nothing calls this directly
no test coverage detected