agc*_*nti 31
像这样的测试视图将起作用:
from django.http import HttpResponse
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponse(status=500)
Run Code Online (Sandbox Code Playgroud)
或者在错误类中使用烘焙:
from django.http import HttpResponseServerError
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponseServerError()
Run Code Online (Sandbox Code Playgroud)
老问题,但我希望这对将来的人有帮助。接受的答案并没有真正回答原来的问题...您可以通过引发 ApiException 轻松地使用 django Rest 框架来做到这一点:
from rest_framework.exceptions import APIException
try:
...
except ...:
raise APIException('custom exception message')
Run Code Online (Sandbox Code Playgroud)
从您的角度来看,这将返回状态为 500 的响应。如果您从 API 调用另一个函数并且您不想管理此函数的返回值来决定是否返回状态为 500 的响应,则非常有用。您可以像这样使用它:
raise ApiException
Run Code Online (Sandbox Code Playgroud)
默认响应消息(在撰写本文时)将为“发生服务器错误”。
有一些预定义的 ApiException 子类可以引发不同类型的错误,请检查文件rest_framework.exceptions,如果您需要其中不存在的子类,您可以像这样扩展 ApiException :
from rest_framework.exceptions import APIException
class YourCustomApiExceptionName(APIException):
def __init__(self, status, detail):
self.status_code = status
self.detail = detail
Run Code Online (Sandbox Code Playgroud)
用法:
raise YourCustomApiExceptionName(100, 'continue')
Run Code Online (Sandbox Code Playgroud)
您还可以定义自定义状态和详细信息,但在大多数情况下没有多大意义。
编辑:
如果由于某种原因您在没有 DRF 的情况下工作,您只需复制 APIException 代码而不是安装 DRF 包:
| 归档时间: |
|
| 查看次数: |
17697 次 |
| 最近记录: |