Error handling

Python में APIs परिचय

Chris Ramakers

Engineering Manager

Error status codes

4xx Client Errors


  • क्लाइंट की ओर की समस्या दर्शाते हैं
  • सामान्य कारण: Bad requests, authentication failures, आदि

समाधान: रिक्वेस्ट ठीक करें

5xx Server Errors


  • सर्वर-साइड समस्याओं से उत्पन्न होते हैं
  • सामान्य कारण: सर्वर ओवरलोड, सर्वर कॉन्फ़िगरेशन त्रुटियाँ, आंतरिक त्रुटियाँ

समाधान: API एडमिनिस्ट्रेटर को ठीक करना चाहिए

Python में APIs परिचय

Error status codes: examples

4xx Client Errors


  • 401 Unauthorized - रिक्वेस्ट में अनुरोधित संसाधन के लिए वैध authentication credentials नहीं हैं
  • 404 Not Found - दर्शाता है कि सर्वर अनुरोधित संसाधन नहीं ढूँढ सका
  • 429 Too Many Requests - क्लाइंट ने दिए गए समय में बहुत अधिक रिक्वेस्ट भेज दीं

5xx Server Errors


  • 500 Internal Server Error - अप्रत्याशित समस्या के कारण सर्वर रिस्पॉन्ड नहीं कर पा रहा है
  • 502 Bad Gateway - API सर्वर उस दूसरे सर्वर तक सफलतापूर्वक नहीं पहुँच सका जिसकी रिस्पॉन्स पूरी करने के लिए ज़रूरत थी
  • 504 Gateway Timeout - गेटवे की तरह काम कर रहा सर्वर upstream सर्वर से समय पर रिस्पॉन्स नहीं पा सका
Python में APIs परिचय

Handling errors

API errors

import requests

url = 'http://api.music-catalog.com/albums'

r = requests.get(url)

if r.status_code >= 400: # Oops, something went wrong
else: # All fine, let's do something # with the response

Connection errors

import requests

from requests.exceptions import ConnectionError
url = ''
try: r = requests.get(url) print(r.status_code)
except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.') print(error)
Python में APIs परिचय

raise_for_status()

import requests

# 1: Import the requests library exceptions from requests.exceptions import ConnectionError, HTTPError
try:
r = requests.get("http://api.music-catalog.com/albums")
# 2: Enable raising exceptions for returned error statuscodes r.raise_for_status()
print(r.status_code)
# 3: Catch any connection errors except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.')
# 4: Catch error responses from the API server except HTTPError as http_err: print(f'HTTP error occurred: {http_err}')
Python में APIs परिचय

अभ्यास करते हैं!

Python में APIs परिचय

Preparing Video For Download...