【问题标题】:Custom exceptions in python starlettepython starlette中的自定义异常
【发布时间】:2020-04-08 16:09:59
【问题描述】:

我正在尝试使用 python 中的 starlette 框架引发自定义异常。我有检查某些条件的 API 调用取决于结果,它应该引发异常。 我有两个文件 app.py 和 error.py

#app.py
        from starlette.applications import Starlette
        from starlette.responses import JSONResponse
        from starlette.routing import Route

        from error import EmptyParamError

        async def homepage(request):

          a=1
          b=0

          if a == 1:
             raise EmptyParamError(400, "status_code")

         return JSONResponse({'hello': 'world'})


        routes = [
           Route("/", endpoint=homepage)
        ]

       app = Starlette(routes=routes,debug=True)`

#error.py ```
from starlette.responses import JSONResponse

class BaseError(Exception):
    def __init__(self, status_code: int, detail: str = None) -> None:
        if detail is None:
          detail = "http.HTTPStatus(status_code).phrase"
       self.status_code = status_code
       self.detail = detail

    async def not_found(self):
       return JSONResponse(content=self.title, status_code=self.status_code)



 class EmptyParamError(BaseError):
         """ Error is raised when group name is not provided. """
        status_code = 400
        title = "Missing Group Name"

当条件为真时,我想引发异常,但它不返回 jsonrespnse,而是返回控制台上的堆栈跟踪。 如果这里有什么问题,请告诉我

【问题讨论】:

    标签: python-3.x api exception starlette


    【解决方案1】:

    添加 try 块解决了问题

       try:
            if a==1:
                raise InvalidUsage(100,"invalid this one")
    
            if b == 0:
                raise EmptyParamError("this is empty paramuvi")
        except InvalidUsage as e:
            return JSONResponse({'hello': str(e.message)})
        except EmptyParamError as e:
            return JSONResponse({'hello': str(e.message)})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多