<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d" -->

---
title: Fetch API, do you really know how to handle errors?
description: Learn how to handle errors when using the Fetch API and understand the best practices for error handling. Discover different approaches, such as using...
canonical: https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: Fetch API, do you really know how to handle errors? | daily.dev
og:description: Learn how to handle errors when using the Fetch API and understand the best practices for error handling. Discover different approaches, such as using...
og:url: https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d
og:image: https://api.daily.dev/og/posts/4O6KWEl5D.png
og:image:alt: Fetch API, do you really know how to handle errors?
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Fetch API, do you really know how to handle errors?

**[DEV](https://daily.dev/sources/devto)** · 5 min read · 415 upvotes · 18 comments

## Summary

Learn how to handle errors when using the Fetch API and understand the best practices for error handling. Discover different approaches, such as using try/catch and checking the response status, and how to combine them for better error handling.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://dev.to/dionarodrigues/fetch-api-do-you-really-know-how-to-handle-errors-2gj0>

## Community discussion

Top comments from developers on daily.dev.

**@caley** · 3 upvotes

> One method I have started to use which I prefer to nesting is to chain on a .catch to the end even when using await. Then you can do an assertion on what comes back
>
>
> `const expected = await myPromise().catch(()=>({error: 'error'}))`

**@maxalieksieiev** · 2 upvotes

> It is a good article. I took a couple of things.

**@lalami** · 1 upvotes

> check here advanced way to handle fetch error in react app : [https://github.com/idurar/idurar-erp-crm/blob/master/frontend/src/request/request.js](https://github.com/idurar/idurar-erp-crm/blob/master/frontend/src/request/request.js)
>
>
> IDURAR  is open source erp crm based on mern-stack Node.js React.js MongoDB ANT Design :  [https://github.com/idurar/idurar-erp-crm](https://github.com/idurar/idurar-erp-crm)
>
> ![Screenshot 2024-01-17 at 10.34.47 AM](https://res.cloudinary.com/daily-now/image/upload/s--L0g90BJa--/f_auto/v1705484105/ugc/content_5d984065-cd82-4528-9051-0ea96ff7c6a4)

**@kaitoai** · 1 upvotes

> Hello, good article.
> I have something to share with you guys, a optimized method to fetch data from api in javascript:
>
> ## The function
> ```javascript
> async function fetchApiData(url, options = {}, retries = 3, backoff = 300) {
>     try {
>         const response = await fetch(url, options);
>         if (!response.ok) { // or check for specific status codes if needed
>             throw new Error(`HTTP error! status: ${response.status}`);
>         }
>         return await response.json();
>     } catch (error) {
>         if (retries > 0) {
>             console.warn(`Retrying... (${retries} attempts left)`,...

**@dishadutta** · 0 upvotes

> good article

## Similar posts on daily.dev

- [Don’t just attend KubeCon \+ CloudNativeCon, Merge Forward your experience\!](https://daily.dev/posts/don-t-just-attend-kubecon-cloudnativecon-merge-forward-your-experience--l0rpp73x8) · CNCF · 1 upvotes · 0 comments
- [Announcing H2 2026 KCDs](https://daily.dev/posts/announcing-h2-2026-kcds-m96goajm1) · CNCF · 1 upvotes · 0 comments
- [Two months of Open Community Groups](https://daily.dev/posts/two-months-of-open-community-groups-asf52zhbs) · CNCF · 0 upvotes · 0 comments

---

Tags: [#webdev](https://daily.dev/tags/webdev), [#javascript](https://daily.dev/tags/javascript), [#frontend](https://daily.dev/tags/frontend)

[View this post on daily.dev](https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"Fetch API, do you really know how to handle errors?","url":"https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d"},"datePublished":"2023-12-01T07:35:09.637Z","dateModified":"2023-12-01T07:35:08.187Z","description":"Learn how to handle errors when using the Fetch API and understand the best practices for error handling. Discover different approaches, such as using...","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/3ec78e24596cb5c25d3603a2645c601d?_a=AQAEufR","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/3ec78e24596cb5c25d3603a2645c601d?_a=AQAEufR","isAccessibleForFree":true,"articleSection":"DEV","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"DEV","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/devto","url":"https://daily.dev/sources/devto"},"commentCount":18,"discussionUrl":"https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":415},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":18}],"keywords":"webdev,javascript,frontend","timeRequired":"PT5M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"DEV","item":"https://daily.dev/sources/devto"},{"@type":"ListItem","position":3,"name":"Fetch API, do you really know how to handle errors?"}]}
{"@context":"https://schema.org","@type":"WebPage","@id":"https://daily.dev/posts/fetch-api-do-you-really-know-how-to-handle-errors--4o6kwel5d","comment":[{"@type":"Comment","text":"One method I have started to use which I prefer to nesting is to chain on a .catch to the end even when using await. Then you can do an assertion on what comes back\nconst expected = await myPromise().catch(()=&gt;({error: 'error'}))","datePublished":"2023-12-07T10:10:24.325Z","url":"https://daily.dev/posts/4O6KWEl5D#c-kMSZRfiMu","author":{"@type":"Person","name":"dsfsasd","url":"https://daily.dev/caley","image":"https://media.daily.dev/image/upload/s--O0TOmw4y--/f_auto/v1715772965/public/noProfile"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":3}},{"@type":"Comment","text":"It is a good article. I took a couple of things.","datePublished":"2023-12-06T21:05:28.454Z","url":"https://daily.dev/posts/4O6KWEl5D#c-MChX7fbqH","author":{"@type":"Person","name":"Максим Алєксєєв","url":"https://daily.dev/maxalieksieiev","image":"https://avatars.githubusercontent.com/u/65343519?v=4"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":2}},{"@type":"Comment","text":"check here advanced way to handle fetch error in react app : https://github.com/idurar/idurar-erp-crm/blob/master/frontend/src/request/request.js\nIDURAR  is open source erp crm based on mern-stack Node.js React.js MongoDB ANT Design :  https://github.com/idurar/idurar-erp-crm","datePublished":"2024-01-17T10:46:08.613Z","url":"https://daily.dev/posts/4O6KWEl5D#c-t6n7b9bnm","author":{"@type":"Person","name":"Lalami Salah Eddine","url":"https://daily.dev/lalami","image":"https://lh3.googleusercontent.com/a-/AOh14GgbUALBr_YEA1ulijeIm0BlwfH2SI72ejUTwmMC=s100"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":1}},{"@type":"Comment","text":"Hello, good article.\nI have something to share with you guys, a optimized method to fetch data from api in javascript:\nThe function\nasync function fetchApiData(url, options = {}, retries = 3, backoff = 300) {\n    try {\n        const response = await fetch(url, options);\n        if (!response.ok) { // or check for specific status codes if needed\n            throw new Error(`HTTP error! status: ${response.status}`);\n        }\n        return await response.json();\n    } catch (error) {\n        if (retries &gt; 0) {\n            console.warn(`Retrying... (${retries} attempts left)`, error);\n            await new Promise(resolve =&gt; setTimeout(resolve, backoff));\n            return fetchApiData(url, options, retries - 1, backoff * 2);\n        } else {\n            console.error(&#x27;API request failed:&#x27;, error);\n            throw error;\n        }\n    }\n}\n\nUsage\nfetchApiData(&#x27;https://api.example.com/data&#x27;)\n    .then(data =&gt; console.log(&#x27;Fetched data:&#x27;, data))\n    .catch(error =&gt; console.error(&#x27;Failed to fetch data:&#x27;, error));\n\n1. options Argument\nThe options argument in the fetchApiData function is an object that allows you to customize various aspects of the HTTP request. This can include:\nMethod: The HTTP method to use, such as GET, POST, PUT, DELETE, etc.\nHeaders: Any HTTP headers you want to set for the request, typically including content type or authentication tokens.\nBody: The body of the request, which is necessary for methods like POST or PUT. It’s usually in JSON format.\nMode: The mode you want to use for the request, such as cors, no-cors, or same-origin.\nCredentials: Indicates whether the browser should send cookies with the request. Options include same-origin, include, or omit.\nCache: Dictates how the request should interact with the browser’s cache.\nExample:\nlet options = {\n    method: &#x27;POST&#x27;,\n    headers: { &#x27;Content-Type&#x27;: &#x27;application/json&#x27; },\n    body: JSON.stringify(data)\n};\n\n2. retries Argument\nThe retries argument is a number that specifies how many times the function should attempt to re-fetch the data in case of a failure. This is useful for handling transient errors or network issues that might temporarily disrupt the API service. After each failed attempt, the function waits for a specified duration (controlled by the backoff argument) before trying again.\n3. backoff Argument\nThe backoff argument is used to implement an exponential backoff strategy. This is a technique where the time interval between retries progressively increases. It helps to efficiently manage server load and network congestion. The initial backoff delay is set by this argument, and with each retry, this delay is doubled.\nFor instance, if backoff is initially set to 300 milliseconds, the delays between retries will be 300ms, 600ms, 1200ms, and so on. This prevents the client from repeatedly hitting the server in quick succession, which can exacerbate network or server issues.\nThanks again for the article :)","datePublished":"2024-01-19T09:50:30.501Z","dateModified":"2024-01-19T09:51:31.526Z","url":"https://daily.dev/posts/4O6KWEl5D#c-F4PfBGoRz","author":{"@type":"Person","name":"ABDELLATIF LAGHJAJ","url":"https://daily.dev/kaitoai","image":"https://media.daily.dev/image/upload/s--cyXjE_59--/f_auto/v1785846816/avatars/avatar_TDGeo0OKoxGLDKFCGEVny?_a=BAMAMicg0"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":1}},{"@type":"Comment","text":"good article","datePublished":"2024-01-07T16:41:47.453Z","url":"https://daily.dev/posts/4O6KWEl5D#c-yDmUfgyCz","author":{"@type":"Person","name":"Disha Dutta","url":"https://daily.dev/dishadutta","image":"https://avatars.githubusercontent.com/u/47849740?v=4"}}]}
```

