Sanic官翻-异常

异常

异常可以从请求处理程序中引发,并由Sanic自动处理。异常将消息作为第一个参数,也可以将状态代码作为HTTP响应传递回去。

抛出异常

要抛出异常,只需从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装饰器。装饰器期望将异常列表作为参数处理。您可以通过SanicException来捕获它们!装饰的异常处理程序函数必须将RequestException对象作为参数。

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()

有用的异常

下面列出了一些最有用的异常

  • NotFound

在找不到适合该请求的路由时调用。

  • ServerError

服务器内部出现问题时调用。如果用户代码中引发异常,通常会发生这种情况。

有关要抛出的异常的完整列表,请参见sanic.exceptions模块。

原文地址:https://www.cnblogs.com/fhkankan/p/14763597.html