使用 Requests 處理錯誤
當 requests 函式庫無法連線到 API 伺服器時,會拋出例外。透過這個例外,你可以檢查 API 是否可用,並採取相應的處理。不過,即使請求已成功送出,仍可能遇到錯誤。如果我們送出無效的請求,API 會回傳 4xx Client Error;若伺服器發生錯誤,則會回傳 5xx Server Error。
requests 套件提供了一組可用的[內建例外](https://requests.readthedocs.io/en/latest/user/quickstart/#errors-and-exceptions),你可以搭配 try/except 陳述式來處理這些錯誤。
為了方便你,requests 套件已經匯入。
本練習屬於課程
Python API 入門
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the correct exception class
from ____ import ____
url ="http://wronghost:3000/albums"
try:
r = requests.get(url)
print(r.status_code)
# Use the imported class to intercept the connection error
except ____ as conn_err:
print(f'Connection Error! {conn_err}.')