File size: 1,841 Bytes
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""Standardized error responses for the API.

All endpoints return consistent error format:
{
  "success": false,
  "error": "Human-readable message",
  "code": "MACHINE_READABLE_CODE",  // optional
  "remaining_requests": 95,           // optional (rate limit info)
}

This ensures both middleware errors and route errors have the same shape
so the frontend always reads from `response.error`.
"""

from fastapi import HTTPException, status
from typing import Any, Dict, Optional


class AppError(Exception):
    """Custom application-level error with machine-readable code."""
    def __init__(
        self,
        message: str,
        code: str = "UNKNOWN_ERROR",
        status_code: int = status.HTTP_400_BAD_REQUEST,
    ):
        self.message = message
        self.code = code
        self.status_code = status_code


def error_response(message: str, code: Optional[str] = None, remaining: Optional[int] = None) -> Dict[str, Any]:
    """Build a standardized error dict."""
    result = {"success": False, "error": message}
    if code:
        result["code"] = code
    if remaining is not None:
        result["remaining_requests"] = remaining
    return result


def raise_error(message: str, code: str = "UNKNOWN_ERROR", status_code: int = 400):
    """Raise an HTTPException with standardized format."""
    raise HTTPException(
        status_code=status_code,
        detail=error_response(message, code),
    )


# Common error codes
class ErrorCode:
    INVALID_CREDENTIALS = "INVALID_CREDENTIALS"
    DUPLICATE_EMAIL = "DUPLICATE_EMAIL"
    TOKEN_EXPIRED = "TOKEN_EXPIRED"
    TOKEN_INVALID = "TOKEN_INVALID"
    RATE_LIMITED = "RATE_LIMITED"
    NOT_FOUND = "NOT_FOUND"
    NOT_AUTHORIZED = "NOT_AUTHORIZED"
    NETWORK_ERROR = "NETWORK_ERROR"
    VALIDATION_ERROR = "VALIDATION_ERROR"
    DB_ERROR = "DATABASE_ERROR"