tar*_*ghs 7 api django django-rest-framework
我想在 DRF 中创建自定义异常。正如 DRF 文档所述,我可以通过创建用户定义的类并继承 APIException 来做到这一点。
效果很好,但问题是我的应用程序要求我发送某种类型的自定义代码以及 HTTP 状态代码。例如,当创建 ProductCatalog 时发生错误时,它应该返回类似这样的内容以及 HTTP 状态代码。
{"code": 4026, "message": "Unable to create catalog"}
Run Code Online (Sandbox Code Playgroud)
这样的事情是必需的,因为虽然我的 API 工作正常,因此 http 状态代码将为 200,但有一些业务逻辑未实现,因此我需要返回某种自定义代码和消息,以便让客户端应用程序相应地处理它。
任何形式的帮助将不胜感激。
我自己想出来了。通过查看代码,我发现如果将default_detail设置为字典,它将按原样返回。
就我而言,会是这样的。
class ProductCatalogExeption(APIException):
status_code = 200 #or whatever you want
default_code = '4026'
# Custom response below
default_detail = {"code": 4026, "message": "Unable to create catalog"}
Run Code Online (Sandbox Code Playgroud)
因此,当引发 ProductCatalogException 时,它将返回
{"code": 4026, "message": "Unable to create catalog"}
Run Code Online (Sandbox Code Playgroud)
HTTP 响应代码 200
供参考: https: //github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py
您可以考虑创建自定义异常处理程序以及自定义异常。像这样:
首先创建异常处理程序来处理 DRF 的错误:
# custom handler
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.default_code
return response
Run Code Online (Sandbox Code Playgroud)
然后更新settings.py该错误
# settings.py
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
Run Code Online (Sandbox Code Playgroud)
最后,创建一个自定义异常,并在需要引发目录创建错误时使用它:
# Custom exception
from rest_framework.exceptions import APIException
class CatalogExeption(APIException):
status_code = 503
default_detail = 'Unable to create catalog'
default_code = '4026'
Run Code Online (Sandbox Code Playgroud)
可以在文档中找到有关自定义异常的更多信息。
| 归档时间: |
|
| 查看次数: |
9124 次 |
| 最近记录: |