11.3 HttpException
1.first_ot_404的异常抛出流程
我们来接着看Aborter类中的firstot_404流程,在first_ot_404调用流程中,由于不满足\_call__的前两个判断条件,最终会抛出self.mapping,其在构造函数中进行了声明
class Aborter(object):
"""
When passed a dict of code -> exception items it can be used as
callable that raises exceptions. If the first argument to the
callable is an integer it will be looked up in the mapping, if it's
a WSGI application it will be raised in a proxy exception.
The rest of the arguments are forwarded to the exception constructor.
"""
def __init__(self, mapping=None, extra=None):
if mapping is None:
mapping = default_exceptions
self.mapping = dict(mapping)
if extra is not None:
self.mapping.update(extra)
def __call__(self, code, *args, **kwargs):
if not args and not kwargs and not isinstance(code, integer_types):
raise HTTPException(response=code)
if code not in self.mapping:
raise LookupError('no exception for %r' % code)
raise self.mapping[code](*args, **kwargs)self.mapping是一个dict,其封装了default_exceptions,下面来看一下default_exceptions的装载,在_find_exceptions中完成。他的作用是扫描当前模块下所有HTTPException的子类对象,并装载到default_exceptions
最终Aborter函数的__call__方法拿着封装好的self.mapping(实质是default_exceptions)通过参数传来的code去匹配相应的异常,并进行抛出。
以下为first_ot_404的总执行流程 
2.抛出异常后到浏览器异常界面的显示流程
因为first_or_404()后面传入Aborter的code为404,所以其对应抛出的异常就是 NotFound对象,而其中的description描述文本,就是异常页面的显示文本
而所有的页面的显示文本,都是由response来做的,我们的试图函数在调用first_or_404()函数时,由于结果不存在,就抛出了上面的NotFound异常而终止了,后面的异常流程直到界面显示,都是由HttpException完成的,来看下其对应源码
get_body()
至此,first_or_404,从调用,到界面显示流程,就剖析完成了
3.基于AOP统一处理异常
如果我们不想返回默认的404界面,而想自己定制,那么直接想到的方法就是在代码中捕获异常,返回我们自定义的试图,但是这样代码太啰嗦了。我们可以采用AOP面向切面的设计思想,定义一个装饰器,用来统一处理某类异常,好在Flask已经为我们提供了这种方法,使用方法如下
Last updated
Was this helpful?