我正在编写一个api。
from rest_framework import exceptions类XYZ(APIView):
authentication_classes = [SessionAuthentication, ]
permission_classes = [IsAuthenticated, ]
api_view = ['GET']
def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
BODY OF API
except Exception as e:
print("---",e)
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST)
def validate_payer(db,request,payer,userid):
organisations = ReportUtils.get_payer_and_company(db,request =request,userid = userid,payer=True)
if len(organisations) == 0:
raise exceptions.NotAcceptable(AppResponse.msg(request, 406, 'No payer associated with the user.', 0, 0, 0))现在我想知道如果异常是从validate引发的
_
payer函数,那么它就不应该进入XYZ(APIView)类中的except块,当由于pi的主体而发生任何其他异常时,它应该转到except块并返回错误请求。什么?
发布于 2021-03-01 14:46:47
我们可以使用
isinstance
内置函数。
def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
BODY OF API
except Exception as e:
if isinstance(e,exceptions.NotAcceptable):
raise
elif isinstance(e,exceptions.PermissionDenied):
raise
else:
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST)因此,如果异常属于NotAcceptable或PermissionDenied类,它将再次引发异常,否则将给出通用消息
出了点问题
状态码
400
发布于 2021-03-01 15:34:54
python中的块可以有多个except子句,抛出的异常通过这些子句,直到遇到第一个匹配的子句。
对于应该重新引发(或需要其他特定处理)而不是由异常处理程序处理的单个异常,以下代码应该可以工作。
def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
# BODY OF API
except exceptions.NotAcceptable:
# Handle NotAcceptable.
raise
except Exception as e:
# Handle all other exceptions.
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST如果多个异常需要相同的异常处理程序,则可以将异常类替换为多个异常类的元组。
def get(self, request):
try:
payer_data = validate_payer(db=db,request =request,payer = payer,userid = userid)
# BODY OF API
except (exceptions.NotAcceptable, exceptions.PermissionDenied):
# Handle NotAcceptable and PermissionDenied.
raise
except Exception as e:
# Handle all other exceptions.
manager.create_from_exception(e)
return Response(AppResponse.msg(request, 400, 'Something went wrong.', 0, 0, 0), status=status.HTTP_400_BAD_REQUEST注意
:
将始终匹配从它派生的每个异常,因此它应该始终放在最后。
https://stackoverflow.com/questions/66347818
复制相似问题