将异常处理程序分配给类的方法

2024-10-05 12:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有多个函数的类。这些函数将处理类似类型的异常。我可以拥有一个处理函数并将其分配给函数吗

最后,我希望函数中不应有异常处理,但在异常时,控件应转到该处理函数

Class Foo:
  def a():
    try:
      some_code
    except Exception1 as ex:
      log error
      mark file for error
      other housekeeping
      return some_status, ex.error
    except Exception2 as ex:
      log error
      mark file for error
      other housekeeping
      return some_status, ex.error

类似地,其他函数也会有同样的异常。我想在一个单独的方法中处理所有这些异常。只是函数应该将控制权移交给异常处理函数

我可以考虑从包装处理函数调用每个函数。但我觉得这很奇怪

Class Foo:
  def process_func(func, *args, **kwargs):
    try:
      func(*args, **kwargs)
    except Exception1 as ex:
      log error
      mark file for error
      other housekeeping
      return some_status, ex.error
    except Exception2 as ex:
      log error
      mark file for error
      other housekeeping
      return some_status, ex.error

  def a(*args, **kwargs):
    some_code

有更好的方法吗


Tags: 函数logforreturnasstatuserrorsome
1条回答
网友
1楼 · 发布于 2024-10-05 12:16:56

您可以定义函数装饰器:

def process_func(func):
    def wrapped_func(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except ...
    return wrapped_func

并用作:

@process_func
def func(...):
   ...

因此func(...)等价于process_func(func)(...),错误在wrapped_func内处理

相关问题 更多 >

    热门问题