dify插件初步构建
This commit is contained in:
42
difyPlugin/app/core/exceptions.py
Normal file
42
difyPlugin/app/core/exceptions.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""自定义异常和异常处理器"""
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.schemas.base import ResultDomain
|
||||
|
||||
|
||||
class BusinessException(Exception):
|
||||
"""业务异常"""
|
||||
def __init__(self, code: int = 500, message: str = "业务异常"):
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
class NotFoundException(BusinessException):
|
||||
"""资源不存在异常"""
|
||||
def __init__(self, message: str = "资源不存在"):
|
||||
super().__init__(code=404, message=message)
|
||||
|
||||
|
||||
class ValidationException(BusinessException):
|
||||
"""参数校验异常"""
|
||||
def __init__(self, message: str = "参数校验失败"):
|
||||
super().__init__(code=400, message=message)
|
||||
|
||||
|
||||
def register_exception_handlers(app: FastAPI):
|
||||
"""注册全局异常处理器"""
|
||||
|
||||
@app.exception_handler(BusinessException)
|
||||
async def business_exception_handler(request: Request, exc: BusinessException):
|
||||
return JSONResponse(
|
||||
status_code=200,
|
||||
content=ResultDomain.fail(message=exc.message, code=exc.code).model_dump()
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def global_exception_handler(request: Request, exc: Exception):
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=ResultDomain.fail(message=str(exc), code=500).model_dump()
|
||||
)
|
||||
Reference in New Issue
Block a user