Python Django rest API中的内部函数raise
如何在Django rest框架中捕捉API内部函数中的4XX系列提升Python Django rest API中的内部函数raise,python,django,django-rest-framework,Python,Django,Django Rest Framework,如何在Django rest框架中捕捉API内部函数中的4XX系列提升 from rest_framework.exceptions import ValidationError class DummyView(APIView): def get(self, request, id): if id==something: dummy_function_1(id) else: dummy_fun
from rest_framework.exceptions import ValidationError
class DummyView(APIView):
def get(self, request, id):
if id==something:
dummy_function_1(id)
else:
dummy_function_2(id)
return Response()
def dummy_function_1():
try:
validate_1(id)
except ValidationError:
raise ValidationError()
#do something with id
return id
当我发送HTTP GET请求时,如果发生异常,我会收到一个5XX系列错误。我想得到400个错误请求的响应。经过大量努力,我不知道为什么, 如果我指定内部函数的异常类型,我将得到5XX系列错误。 在虚拟函数中,我刚刚写到:
def dummy_function_1():
try:
validate_1(id)
except Exception: # just exception, Not ValidationError or other exception
raise ValidationError()
我可能会遇到4XX系列错误请尝试以下操作:
def dummy_function_1():
try:
validate_1(id)
except Exception: # just exception, Not ValidationError or other exceptions
raise ValidationError()
为什么不在get函数中添加try-except语句并在其中处理异常?因为我在多个地方使用此函数,这就是我需要它的原因。这可能对@crazychukz有帮助,我读了它,它对我没有帮助。如果我非常了解你,你想更改错误状态代码吗?