首頁 >後端開發 >Python教學 >使用Python的Requests模組時如何優雅地處理錯誤?

使用Python的Requests模組時如何優雅地處理錯誤?

DDD
DDD原創
2024-11-12 11:54:02509瀏覽

How to Handle Errors Gracefully When Using Python's Requests Module?

使用 Python 的 Requests 模組捕獲錯誤

使用 requests 模組發出 HTTP 請求時,優雅地處理錯誤至關重要。 try/ except 結構可讓您捕捉錯誤並做出適當的回應。

try/ except 的正確用法

提供的使用 try/ except 捕獲請求的範例。 ConnectionError是正確但有限的。雖然它會捕獲與網路相關的問題,但它不會涵蓋其他錯誤類型,例如逾時或太多重定向。

涵蓋所有異常

捕獲所有請求-相關錯誤,您可以使用基類異常requests.exceptions.RequestException:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:
    # Handle the error accordingly

處理特定錯誤

或者,您可以單獨捕獲特定錯誤類型:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Retry or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Prompt the user to correct the URL
except requests.exceptions.RequestException as e:
    # Handle catastrophic errors

捕捉HTTP 錯誤

如果要引發HTTP 錯誤代碼異常(例如401 Unauthorized),請在建立後呼叫Response.raise_for_status()要求:
try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    # Handle the HTTP error

透過實作正確的錯誤處理,您可以確保您的腳本/程式可以有效回應HTTP 請求期間遇到的不同錯誤。

以上是使用Python的Requests模組時如何優雅地處理錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn