Catch exceptions inside a class

后端 未结 3 893
别跟我提以往
别跟我提以往 2020-12-29 06:53

Is it possible to write an exception handler to catch the run-time errors generated by ALL the methods in class? I can do it by surrounding each one with try/except:

3条回答
  •  渐次进展
    2020-12-29 07:10

    Assuming you've got a decorator catch_exception as in @Jon Clement's answer...

    class ErrorCatcher(type):
        def __new__(cls, name, bases, dct):
            for m in dct:
                if hasattr(dct[m], '__call__'):
                    dct[m] = catch_exception(dct[m])
            return type.__new__(cls, name, bases, dct)
    
    class Test(object):
        __metaclass__ = ErrorCatcher
    
        def __init__(self, val):
            self.val = val
    
        def calc(self):
            return self.val / 0
    

    The metaclass applies catch_exception to everything that appears to be a method while it is defining Test.


    In response to a comment regarding custom messages for each method, one could attach such a message (or even a callback function to generate a message) as an attribute:

    class Test(object):
        __metaclass__ = ErrorCatcher
        def __init__(self, val):
            self.val = val
    
        def calc(self):
            return self.val / 0
    
        calc.msg = "Dividing by 0 is ill-advised"
    

    The catch_exception decorator would look for a msg attribute on its argument and use it, if found, in handling the exception.

    This approach could be extended; instead of a string, msg could be a mapping of exception types to strings. In either case, the string could be replaced (with support from catch_exception, of course) with an arbitrary callback function that takes, say, the raised exception as an argument.

    def calc_handler(exc):
        # ...
    
    calc.callback = calc_handler
    

提交回复
热议问题