|
8 | 8 | from fastapi.middleware.cors import CORSMiddleware |
9 | 9 | from fastapi.middleware.gzip import GZipMiddleware |
10 | 10 | from fastapi.openapi.utils import get_openapi |
11 | | -from fastapi.responses import PlainTextResponse |
12 | 11 | from fastapi.routing import APIRoute |
13 | 12 | from loguru import logger |
14 | 13 | from psycopg2.errors import UniqueViolation |
15 | 14 | from sqlalchemy.exc import IntegrityError |
16 | 15 | from starlette.middleware.sessions import SessionMiddleware |
17 | 16 | from uvicorn.main import run |
18 | 17 |
|
19 | | -from common.exception_handler import exception_handlers |
| 18 | +from common.exception_handler import exception_handler, exception_handlers |
20 | 19 | from repos.elastic.elastic_repo import ElasticSearchRepo |
21 | 20 | from repos.llm_repo import LLMRepo |
22 | 21 | from utils.import_utils import import_by_suffix |
@@ -118,21 +117,16 @@ def custom_openapi(): |
118 | 117 | app.include_router(em.router) |
119 | 118 |
|
120 | 119 |
|
121 | | -@app.exception_handler(IntegrityError) |
122 | | -async def integrity_error_handler(_, exc: IntegrityError): |
123 | | - logger.exception(exc) |
124 | | - if isinstance(exc.orig, UniqueViolation): |
125 | | - msg = str(exc.orig.pgerror).split("\n")[1] |
126 | | - return PlainTextResponse(msg, status_code=409) |
127 | | - else: |
128 | | - return PlainTextResponse(str(exc), status_code=500) |
129 | | - |
130 | | - |
131 | | -@app.exception_handler(NoSuchJobError) |
132 | | -async def no_such_job_error_handler(_, exc: NoSuchJobError): |
133 | | - logger.exception(exc) |
134 | | - return PlainTextResponse(str(exc), status_code=404) |
| 120 | +exception_handler( |
| 121 | + http_status_code=lambda exc: 409 |
| 122 | + if isinstance(exc, IntegrityError) and isinstance(exc.orig, UniqueViolation) |
| 123 | + else 500, |
| 124 | + extract_message=lambda exc: str(exc.orig.pgerror).split("\n")[1] |
| 125 | + if isinstance(exc, IntegrityError) and isinstance(exc.orig, UniqueViolation) |
| 126 | + else str(exc), |
| 127 | +)(IntegrityError) |
135 | 128 |
|
| 129 | +exception_handler(404)(NoSuchJobError) |
136 | 130 |
|
137 | 131 | # register all exception handlers in fastAPI |
138 | 132 | for ex_class, handler_func in exception_handlers: |
|
0 commit comments