防止在使用python装饰器时引发重复异常
如果我有一个装饰函数,它会引发一个异常,然后在装饰器中捕获该异常,以便执行一些逻辑。如何使修饰函数仍然返回异常(而不在修饰器中再次引发异常) 修饰函数示例:防止在使用python装饰器时引发重复异常,python,python-decorators,Python,Python Decorators,如果我有一个装饰函数,它会引发一个异常,然后在装饰器中捕获该异常,以便执行一些逻辑。如何使修饰函数仍然返回异常(而不在修饰器中再次引发异常) 修饰函数示例: @ach_api_error() def retrieve(self, request, pk=None): profile = request.user.profile if not pk: raise CustomNotFoundException(detail="Not Fo
@ach_api_error()
def retrieve(self, request, pk=None):
profile = request.user.profile
if not pk:
raise CustomNotFoundException(detail="Not Found.")
return Response(status=status.HTTP_200_OK)
装饰器示例:
def ach_api_error():
def decorate(f):
def applicator(*args, **kwargs):
try:
result = f(*args, **kwargs)
return result
except CustomNotFoundException:
#
# PERFORM SOME EXCEPTION LOGGING HERE
#
raise CustomNotFoundException(detail="Not Found.")
return applicator
return decorate
我希望
decoration()
函数返回异常。如何在不引发两次相同异常的情况下实现这一点?只需将applicator
函数中的raise
行更改为return
@nima这将导致此错误:预期从视图中返回“Response”、“HttpResponse”或“HttpStreamingResponse”,但是收到了一个“
只需将涂抹器
函数中的升高
行更改为返回
@nima这将导致此错误:预期从视图返回一个“响应”、“HttpResponse”或“HttpStreamingResponse”,但收到了一个“