例外情况
异常可以从请求处理程序中抛出,并由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)
# this won't happen
text("OK")
异常处理
要重写Sanic对异常的默认处理,请 @app.exception 使用了decorator。decorator需要一个异常列表作为参数处理。你可以通过 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("error_handler_example")
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("custom_error_handler_example")
app.error_handler = CustomErrorHandler()
有用的例外
以下列出了一些最有用的例外情况:
NotFound :在找不到适合请求的路由时调用。
ServerError :当服务器内部出现问题时调用。如果用户代码中出现异常,则通常会发生这种情况。
见 sanic.exceptions 用于抛出异常的完整列表的模块。