When calling an API from the client side (or from Python), errors will occur —
network failures, invalid parameters, server-side crashes,
authentication issues, etc.
The key is to catch those failures and respond safely instead of letting the code crash.
Client-side (Example using JavaScript fetch)
fetch() does NOT throw an error for HTTP errors (like 400 or 500) — it only throws for network failures. So you must check response.ok.
async function callApi() {
try {
const res = await fetch("https://api.example.com/data", {
method: "GET",
});
// HTTP error (400–599)
if (!res.ok) {
const errorBody = await res.text(); // or res.json() if guaranteed JSON
throw new Error(`API Error: ${res.status} ${res.statusText} - ${errorBody}`);
}
const data = await res.json();
console.log("Success:", data);
}
catch (err) {
// Network error, timeout, CORS failure, etc.
console.error("Request failed:", err.message);
alert("Something went wrong. Please try again.");
}
}
Optional advanced error types
You can categorize errors:
catch(err) {
if (err.message.includes("Failed to fetch")) {
console.log("Network or CORS issue");
} else if (err.message.includes("401")) {
console.log("Not authorized, redirect login");
} else {
console.log("Unexpected:", err);
}
}
Handling API errors in Python
When using requests, you can:
Basic pattern
import requests
try:
r = requests.get("https://api.example.com/data", timeout=10)
r.raise_for_status() # raises HTTPError for 4xx / 5xx responses
data = r.json()
print("Success:", data)
except requests.exceptions.HTTPError as e:
print("API returned error:", r.status_code, r.text)
except requests.exceptions.ConnectionError:
print("Network problem (DNS, refused connection, etc.)")
except requests.exceptions.Timeout:
print("Request timed out")
except requests.exceptions.RequestException as e:
print("Unexpected error:", e)
Full reusable wrapper (recommended)
import requests
def api_call(url, method="get", **kwargs):
try:
r = requests.request(method, url, timeout=10, **kwargs)
r.raise_for_status()
return {"success": True, "data": r.json()}
except requests.exceptions.RequestException as e:
return {"success": False, "error": str(e)}
result = api_call("https://api.example.com/data")
if result["success"]:
print(result["data"])
else:
print("API failed:", result["error"])
General error-handling principles (both JS + Python)
Type of failure
Example
What to do
Network errors
Internet down, DNS failure
Retry or show a message
Timeout
Server too slow
Retry or cancel action
HTTP error
400, 401, 404, 500
Show user-friendly message based on status
Invalid JSON
Server returned HTML instead of JSON
Add fallback and log
Authentication error
Token expired
Refresh token or redirect to login
Quick summary
Language
Error handling
JavaScript (fetch)
try/catch + check response.ok
Python (requests)
try/except + raise_for_status()
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Client-side (Example using JavaScript
fetch)fetch()does NOT throw an error for HTTP errors (like 400 or 500) — it only throws for network failures.So you must check
response.ok.Optional advanced error types
You can categorize errors:
Handling API errors in Python
When using
requests, you can:Basic pattern
Full reusable wrapper (recommended)
General error-handling principles (both JS + Python)
Quick summary
fetch)try/catch+ checkresponse.okrequests)try/except+raise_for_status()