**
10 . 异常
你的鼓励是我前进的动力,请为我点个赞吧!
**
异常可以被视图函数抛出,同时这些异常又可以被Sanic框架自动处理,Exceptions获取第一个参数为错误信息,与此同时可以传递一个状态码返回给Http响应。
(1) 抛出一个异常
使用raise抛出一个异常,异常函数需要从sanic.exception模块进行导入。
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")
(2) 异常处理
重写Sanic的异常处理函数需要使用@app.exception装饰器,装饰器将会把异常当成参数处理,开发者可回传递SanicExceptions替代所有的异常情况,被装饰的异常处理函数必须传递两个参数具体示例如下所示:
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()
(3)经常使用的异常处理函数
- NotFound:请求url未找到
- ServerError:服务器内部错误
通过sanic.exceptions可以查看exceptions的清单。