# 異常
Sanic可以自動地在handler中拋出異常,異常信息會作為它的第一個參數,包含`response`的狀態碼。
## 拋出異常
使用Python自帶的`raise`或者`exceptions.abort()`都可以拋出異常
```python
from sanic.exceptions import ServerError
@app.route('/killme')
def i_am_ready_to_die(request):
raise ServerError("Something bad happened", status_code=500)
@app.route('/youshallnotpass')
def no_no(request):
abort(401)
# 直接返回,后續代碼不會再被執行
text("OK")
```
`about()`封裝了`raise`,會拋出一個基于`SanicException`的異常,除非特別指定,否則返回HTTP狀態碼對應的標準信息(在`response.STATUS_CODES`中設置)。
## 自定義異常
使用`@app.exception`裝飾器,可以覆蓋默認的異常處理程序。這個裝飾器內置了異常列表作為參數,可以通過`SanicException`捕獲它們。被裝飾的方法必須有`Request`和`Exception`兩個對象作為參數。
```python
from sanic.response import text
from sanic.exceptions import NotFound
@app.exception(NotFound)
def ignore_404s(request, exception):
return text("Yep, I totally found the page: {}".format(request.url))
```
## 常用的異常
- `NotFound` 404
- `ServerError` 500
完整的異常列表可參見`sanic.exceptions`