请求处理函数可以抛出异常,它们会被Sanic自动处理。异常以一个文本信息作为第一个参数,同时可以把状态码作为第二个参数并包含在HTTP响应返回给浏览器。
抛出异常
为了抛出异常,只需使用 raise
抛出 sanic.exceptions
模块的相应异常即可。
from sanic.exceptions import ServerError
@app.route('/killme')
async def i_am_ready_to_die(request):
raise ServerError("Something bad happened", status_code=500)
也可以使用传递状态码的 abort
函数:
from sanic.exceptions import abort
from sanic.response import text
@app.route('/youshallnotpass')
async def no_no(request):
abort(401)
# 下面的不再执行
text("OK")
处理异常
为了覆盖 Sanic 对异常的默认处理,可以使用 @app.exception
装饰器。该装饰器需要一个作为参数处理的异常列表。我们可以传递SanicException
来捕获它们。被装饰的异常处理函数必须以request
和exception
作为参数。
from sanic.response import text
from sanic.exceptions import NotFound
@app.exception(NotFound)
async def ignore_404s(request, exception):
return text("Yep, I totally found the page: {}".format(request.url))
我们也可以像下面这样增加一个异常处理函数:
from sanic import Sanic
async def server_error_handler(request, exception):
return text("Oops, server error", status=500)
app = Sanic()
app.error_handler.add(Exception, server_error_handler)
有些时候,我们可能想在默认的异常处理中增加更多的错误处理功能,那么我们就可以继承 Sanic 默认的错误处理器:
from sanic import Sanic
from sanic.handlers import ErrorHandler
class CustomErrorHandler(ErrorHandler):
def default(self, request, exception):
''' handles errors that have no error handlers assigned '''
# You custom error handling logic...
return super().default(request, exception)
app = Sanic()
app.error_handler = CustomErrorHandler()
有用的异常
下面是一些最有用的异常:
NotFund
:当请求的路由没找到时调用。ServerError
: 当服务器内部发生错误时调用。这通常发生在用户代码抛出异常时。
更多的异常可以查看 sanic.exceptions
模块。

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。
***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***
说点什么吧...