如何在像mixin这样的普通类中捕获所有异常

时间:2018-10-11 04:24:35

标签: python django decorator mixins

我在python django应用程序中有基于类的视图。他们中的大多数都处理相同类型的异常,例如:

class A{
    try:
        func1()
    except type1 as e:
        handle1()
    except type2 as e:
        handle()
}

class B{
    try:
        func2()
        func3()
    except type1 as e:
        handle1()
    except type2 as e:
        handle()
}

我想将此异常处理保留在一个通用类中(可能是一个混合类)。哪个类需要异常处理将继承公共类。

将重复的异常处理保持在一个普通的类中。我正在使用python3和django1.11-基于类的视图

2 个答案:

答案 0 :(得分:1)

您可以将异常处理提取到基类并在派生类中更改实现:

In [15]: import abc

In [16]: class Base:
    ...:     def run(self):
    ...:         try:
    ...:             self.do_run()
    ...:         except:
    ...:             print('failed')
    ...:
    ...:     @abc.abstractmethod
    ...:     def do_run(self):
    ...:         ...
    ...:

In [17]: class Foo(Base):
    ...:     def do_run(self):
    ...:         print('run foo')
    ...:

In [18]: class Bar(Base):
    ...:     def do_run(self):
    ...:         print('fail bar')
    ...:         raise Exception()
    ...:

In [19]: f = Foo()

In [20]: f.run()
run foo

In [21]: b = Bar()

In [22]: b.run()
fail bar
failed

答案 1 :(得分:0)

如果使用的是django类基本视图,则可以覆盖dispatch并创建一个mixin。在基于django类的视图中,视图分配方法接受请求并最终返回响应。

您可以执行类似的操作-

class ExceptionHandlingMixin(object):
    def dispatch(self, request, *args, **kwargs):
        try:
            func1()
        except type1 as e:
            handle()
        except type2 as e:
            handle()
        return super(ExceptionHandlingMixin, self).dispatch(request, *args, **kwargs)

以您的方式对此进行修改。供参考,请访问documentation