-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.py
More file actions
68 lines (60 loc) · 2.42 KB
/
Copy pathevents.py
File metadata and controls
68 lines (60 loc) · 2.42 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
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse, FileResponse
from utils.api_response import *
from utils.status_codes import status_codes
from traceback import extract_tb, format_exc
from starlette.exceptions import HTTPException as StarletteHTTPException
from settings import app, settings, templates
import os
@app.get("/favicon", include_in_schema=False)
@app.get("/favicon.ico", include_in_schema=False)
@app.get("/favicon.png", include_in_schema=False)
async def favicon():
return FileResponse("static/images/favicon.png")
@app.exception_handler(StarletteHTTPException)
@app.exception_handler(Exception)
@app.exception_handler(HTTPException)
@app.exception_handler(ApiError)
async def handle_error(request: Request, error: Exception):
status_code = getattr(error, 'status_code', getattr(error, 'code', 500))
data = getattr(error, 'data', getattr(error, 'detail', None))
status_code_data = status_codes[status_code].copy() if status_code in status_codes else None
if not status_code_data:
status_code_data = {
"title": f"{status_code} Error",
"description": "Unknown error"
}
if data and isinstance(data, str) and data != "Unauthorized" and not data.startswith("4"):
status_code_data["description"] = data
elif data and not isinstance(data, str):
status_code_data["description"] = data
if settings["debug"] and (500 <= status_code <= 599):
print(format_exc())
if request.url.path.startswith('/api'):
if settings["debug"] and (500 <= status_code <= 599):
lf = extract_tb(error.__traceback__)[-1]
content = {
"short_message": str(error),
"type": type(error).__name__,
"filename": os.path.basename(lf.filename),
"function_name": lf.name,
"code_line": lf.line.replace('"', "'"),
"line_number": lf.lineno
}
else:
content = status_code_data["title"]
return apiResponse(
content,
status_code,
status_code_data["description"]
)
else:
return templates.TemplateResponse(
"error.html",
{
"request": request,
"status_code": status_code,
"data": status_code_data
},
status_code=status_code
)