|
| 1 | +""" |
| 2 | +Copyright 2024 Maner·Fan |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +""" |
| 16 | + |
| 17 | +import logging |
| 18 | + |
| 19 | +from fastapi import FastAPI |
| 20 | +from fastapi.exceptions import RequestValidationError |
| 21 | +from starlette.responses import JSONResponse |
| 22 | + |
| 23 | +from utils.errors.base_error import BaseServiceError |
| 24 | +from . import auth |
| 25 | + |
| 26 | +log = logging.getLogger() |
| 27 | + |
| 28 | + |
| 29 | +def register(app: FastAPI): |
| 30 | + """ |
| 31 | + 注册路由 |
| 32 | + :param app: FastAPI |
| 33 | + """ |
| 34 | + |
| 35 | + exception_handler(app) |
| 36 | + |
| 37 | + app.include_router(auth.login.router, prefix='/api', tags=['auth | 认证']) |
| 38 | + app.include_router(auth.users.router, prefix='/api/user', tags=['user | 用户']) |
| 39 | + |
| 40 | + |
| 41 | +def exception_handler(app: FastAPI): |
| 42 | + """ |
| 43 | + 定义全局异常处理 |
| 44 | + :param app: FastAPI |
| 45 | + """ |
| 46 | + |
| 47 | + @app.exception_handler(RequestValidationError) |
| 48 | + async def validation_exception_handler(request, exc: RequestValidationError): |
| 49 | + log.warning('RequestValidationError %s, %s', exc.__class__, str(exc)) |
| 50 | + return JSONResponse(str(exc), status_code=400) |
| 51 | + |
| 52 | + @app.exception_handler(BaseServiceError) |
| 53 | + async def service_exception_handler(request, exc: BaseServiceError): |
| 54 | + log.warning('ServiceError %s, %s', exc.__class__, exc.message) |
| 55 | + return JSONResponse({'message': exc.message}, status_code=exc.status_code) |
| 56 | + |
| 57 | + @app.exception_handler(Exception) |
| 58 | + async def common_exception_handler(request, exc: Exception): |
| 59 | + log.exception('ExceptionError %s', str(exc)) |
| 60 | + return JSONResponse({'message': str(exc)}, status_code=500) |
0 commit comments