---
title: "How do you handle errors in an API request (client-side)?"  
description: "How do you handle errors in an API request (client-side)?"  
author: "Anubhav Sharma"  
published: 2025-11-06  
updated: 2025-11-24  
canonical: https://www.mindstick.com/forum/161988/how-do-you-handle-errors-in-an-api-request-client-side  
category: "python"  
tags: ["python-3.4", "Python 3"]  
reading_time: 3 minutes  

---

# How do you handle errors in an API request (client-side)?

**How do you [handle errors](https://www.mindstick.com/forum/157886/how-do-you-handle-errors-and-exceptions-in-angularjs-applications) in an [API](https://www.mindstick.com/articles/12641/instagram-api-upgraded-to-facebook-graph) [request](https://www.mindstick.com/blog/255/post-get-and-request-function-in-php) ([client](https://www.mindstick.com/articles/23198/3-steps-to-ensure-that-your-client-portal-is-impeccable)-side)?**

## Replies

### Reply by ICSM Computer

> When calling an API from the client side (or from Python), **[errors](https://answers.mindstick.com/qa/116170/fresh-fir-against-gandhis-in-national-herald-case-cover-up-for-ed-s-own-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`.

```javascript
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:

```javascript
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

```python
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)

```python
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()` |


---

Original Source: https://www.mindstick.com/forum/161988/how-do-you-handle-errors-in-an-api-request-client-side

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
