我写过
class CustomApiException(APIException):
#public fields
detail = None
status_code = None
# create constructor
def __init__(self, status_code, message):
#override public fields
CustomApiException.status_code = status_code
CustomApiException.detail = message
CustomApiException.message = message
适用于APIView,但对于TemplateView,它会产生错误。编写自定义API异常的正确方法是什么,它将适用于两个视图。
答案 0 :(得分:0)
在您的视图中,将模板视图定义为以下
from django.http import HttpResponseForbidden
#rest of the views
class yourview(TemplateView):
def get(request):
try:
#business logic
except CustomApiException:
return HttpResponseForbidden()
这会引发Error 403
如果要渲染自己的模板而不是引发HttpResponseForbidden
,可以按照以下方式将异常变量传递给视图,并适当地写出视图的响应
class yourview(TemplateView):
def get(request):
try:
#business logic
except CustomApiException as e:
status_code = e.status_code
detail = e.message
message = e.message
#Handle the response here.