forked from OpenBMB/ChatDev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handler.py
More file actions
executable file
·147 lines (112 loc) · 5.25 KB
/
error_handler.py
File metadata and controls
executable file
·147 lines (112 loc) · 5.25 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""Error handling utilities for the DevAll workflow system."""
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
import traceback
from utils.structured_logger import get_server_logger
from utils.exceptions import MACException, ValidationError, SecurityError, ConfigurationError, \
WorkflowExecutionError, ResourceNotFoundError, ResourceConflictError, TimeoutError, ExternalServiceError
# Error code mapping to HTTP status codes
ERROR_CODE_TO_STATUS = {
"VALIDATION_ERROR": 400,
"SECURITY_ERROR": 403,
"CONFIGURATION_ERROR": 500,
"WORKFLOW_EXECUTION_ERROR": 500,
"RESOURCE_NOT_FOUND": 404,
"RESOURCE_CONFLICT": 409,
"TIMEOUT_ERROR": 408,
"EXTERNAL_SERVICE_ERROR": 502,
"GENERIC_ERROR": 500
}
async def handle_validation_error(request: Request, exc: ValidationError) -> JSONResponse:
"""Handle validation errors."""
return await handle_mac_exception(request, exc)
async def handle_security_error(request: Request, exc: SecurityError) -> JSONResponse:
"""Handle security errors."""
return await handle_mac_exception(request, exc)
async def handle_configuration_error(request: Request, exc: ConfigurationError) -> JSONResponse:
"""Handle configuration errors."""
return await handle_mac_exception(request, exc)
async def handle_workflow_execution_error(request: Request, exc: WorkflowExecutionError) -> JSONResponse:
"""Handle workflow execution errors."""
return await handle_mac_exception(request, exc)
async def handle_resource_not_found_error(request: Request, exc: ResourceNotFoundError) -> JSONResponse:
"""Handle resource not found errors."""
return await handle_mac_exception(request, exc)
async def handle_resource_conflict_error(request: Request, exc: ResourceConflictError) -> JSONResponse:
"""Handle resource conflict errors."""
return await handle_mac_exception(request, exc)
async def handle_timeout_error(request: Request, exc: TimeoutError) -> JSONResponse:
"""Handle timeout errors."""
return await handle_mac_exception(request, exc)
async def handle_external_service_error(request: Request, exc: ExternalServiceError) -> JSONResponse:
"""Handle external service errors."""
return await handle_mac_exception(request, exc)
async def handle_mac_exception(request: Request, exc: MACException) -> JSONResponse:
"""Handle DevAll exceptions and return standardized error response."""
logger = get_server_logger()
# Log the error
logger.log_exception(
exc,
f"DevAll exception occurred: {exc.error_code} - {exc.message}",
correlation_id=getattr(request.state, 'correlation_id', None),
url=str(request.url),
method=request.method
)
# Determine the HTTP status code
status_code = ERROR_CODE_TO_STATUS.get(exc.error_code, 500)
# Prepare response data
response_data = {
"error": {
"code": exc.error_code,
"message": exc.message,
"details": exc.details
},
"timestamp": exc.__dict__.get('_timestamp', __import__('datetime').datetime.utcnow().isoformat())
}
return JSONResponse(
status_code=status_code,
content=jsonable_encoder(response_data)
)
async def handle_general_exception(request: Request, exc: Exception) -> JSONResponse:
"""Handle general exceptions and return standardized error response."""
logger = get_server_logger()
# Log the error with traceback
logger.log_exception(
exc,
f"General exception occurred: {type(exc).__name__} - {str(exc)}",
correlation_id=getattr(request.state, 'correlation_id', None),
url=str(request.url),
method=request.method
)
# For security, don't expose internal error details to the client
error_details = {
"code": "INTERNAL_ERROR",
"message": "An internal server error occurred",
"details": {} # Don't send internal details to client
}
# In development, we might want to include more details
import os
if os.getenv("ENVIRONMENT") == "development":
error_details["details"]["debug_info"] = {
"exception_type": type(exc).__name__,
"exception_message": str(exc),
"traceback": traceback.format_exc()
}
return JSONResponse(
status_code=500,
content=jsonable_encoder({"error": error_details})
)
def add_exception_handlers(app):
"""Add exception handlers to FastAPI app."""
app.add_exception_handler(ValidationError, handle_validation_error)
app.add_exception_handler(SecurityError, handle_security_error)
app.add_exception_handler(ConfigurationError, handle_configuration_error)
app.add_exception_handler(WorkflowExecutionError, handle_workflow_execution_error)
app.add_exception_handler(ResourceNotFoundError, handle_resource_not_found_error)
app.add_exception_handler(ResourceConflictError, handle_resource_conflict_error)
app.add_exception_handler(TimeoutError, handle_timeout_error)
app.add_exception_handler(ExternalServiceError, handle_external_service_error)
app.add_exception_handler(MACException, handle_mac_exception)
app.add_exception_handler(Exception, handle_general_exception)
return app