ForcePilot/backend/package/yuxi/channel/extensions/msteams/errors.py

91 lines
2.5 KiB
Python
Raw Normal View History

from __future__ import annotations
import logging
from .types import MSTeamsErrorCode
logger = logging.getLogger(__name__)
MAX_RETRIES = 3
MAX_RETRY_DELAY_MS = 10000
RETRY_BASE_MS = 1000
class MSTeamsError(Exception):
def __init__(self, error_code: MSTeamsErrorCode, message: str, status_code: int | None = None):
self.error_code = error_code
self.status_code = status_code
super().__init__(message)
class MSTeamsAuthError(MSTeamsError):
pass
class MSTeamsThrottledError(MSTeamsError):
pass
class MSTeamsTransientError(MSTeamsError):
pass
class MSTeamsPermanentError(MSTeamsError):
pass
class MSTeamsNetworkError(MSTeamsError):
pass
def classify_http_error(status_code: int, response_body: dict | None = None) -> MSTeamsErrorCode:
if status_code in (401, 403):
return MSTeamsErrorCode.AUTH
if status_code == 429:
return MSTeamsErrorCode.THROTTLED
if status_code in (500, 502, 503, 504):
return MSTeamsErrorCode.SERVICE_UNAVAILABLE
if status_code in (408,):
return MSTeamsErrorCode.TRANSIENT
if status_code == 400:
error_body = response_body or {}
error = error_body.get("error", {})
if isinstance(error, dict):
if error.get("code") == "BadArgument" and "replyToId" in str(error.get("message", "")):
return MSTeamsErrorCode.TRANSIENT
return MSTeamsErrorCode.BAD_REQUEST
if status_code == 404:
return MSTeamsErrorCode.NOT_FOUND
return MSTeamsErrorCode.PERMANENT
def is_retryable(error_code: MSTeamsErrorCode) -> bool:
return error_code in (MSTeamsErrorCode.THROTTLED, MSTeamsErrorCode.TRANSIENT)
def retry_delay_ms(attempt: int) -> int:
return min(RETRY_BASE_MS * (2**attempt), MAX_RETRY_DELAY_MS)
def classify_exception(exc: Exception) -> MSTeamsErrorCode:
import httpx
if isinstance(exc, MSTeamsError):
return exc.error_code
if isinstance(exc, httpx.HTTPStatusError):
return classify_http_error(exc.response.status_code)
if isinstance(exc, httpx.NetworkError) or isinstance(exc, (ConnectionError, TimeoutError)):
return MSTeamsErrorCode.NETWORK
return MSTeamsErrorCode.PERMANENT
def build_error_for_response(status_code: int, body: dict | None = None) -> MSTeamsError:
error_code = classify_http_error(status_code, body)
msg = f"HTTP {status_code}"
if body:
msg += f": {str(body)[:200]}"
return MSTeamsError(error_code, msg, status_code)