赞
踩
Django ninja内置了一些常用异常类。
- from ninja.errors import HttpError
-
- @api.get("/some/resource")
- def some_operation(request):
- if True:
- raise HttpError(503, "Service Unavailable. Please retry later.")
可以覆写内置异常类的handler,改变返回结果的内容。
- from ninja.errors import ValidationError
- ...
-
- @api.exception_handler(ValidationError)
- def validation_errors(request, exc):
- return HttpResponse("Invalid input", status=422)
以创建一个500服务不可用异常类为例。
要实现这一点,你需要:
api.exception_handler
为ServiceUnavailableError异常添加一个处理函数- api = NinjaAPI()
-
- class ServiceUnavailableError(Exception):
- pass
-
-
- # initializing handler
-
- @api.exception_handler(ServiceUnavailableError)
- def service_unavailable(request, exc):
- return api.create_response(
- request,
- {"message": "Please retry later"},
- status=503,
- )
-
-
- # some logic that throws exception
-
- @api.get("/service")
- def some_operation(request):
- if random.choice([True, False]):
- raise ServiceUnavailableError()
- return {"message": "Hello"}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。