What causes a runtime exception when a 500 error is thrown, and why isn't it caught by the promise

I encountered an issue with my api call – the server returned a 500 error. I was hoping to handle this error within a Promise, but instead, I received a runtime error TypeError: Failed to fetch, along with a stack trace which prevented me from retrieving the status code. Is there a way for me to access the Response Instance from the api request that includes the status field without encountering a runtime error?

try {
      window.fetch(url, {
            method: 'POST',
            body,
        }).then((res) => { 
                // I am expecting the response here
        }, (rej) => {
                // Or here
        });
    } catch (e) {
      // In cases where the server responds with a 500 error, it gets handled at this level and not inside the promise block
    }

Answer №1

Since the fetch function works asynchronously, it can exit the try/catch block before resolving or rejecting. To ensure that the code remains inside the try/catch, you must utilize the await keyword like this:

(async () => {
  let data;
  try {
    data = await fetch(url, {
      method: 'GET',
    });
  } catch (error) {
    // Handle errors here
  } finally {
    if(data) {
      // Perform actions with the retrieved data
    }
  }
})()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging React Native's Async Storage to store and retrieve values consistently within the Render method

Is there a way to set and get a value in the render method with just one line of code, by using a variable between tags? I attempted this approach but encountered an error message stating "Can't find variable: storage_key". import React, { Component } ...

Update the icon with the adjusted API information

I am currently working on a website that revolves around the theme of weather. I have reached a point in the development process where I need the icon to change according to the current weather conditions. let updateIcon = () => { let ic ...

Utilizing the classList property with elements that are hidden from view

How can I use JavaScript to toggle between classes? I can't seem to understand why an element that is set to display: none; is unable to receive a class using classList. In simpler terms, if I define #div1{ width: 25%; background-color: #000000; ...

Nested ng-repeat in AngularJS by numeric value

Looking to create a sliding carousel layout for displaying a bunch of data with 8 points per slide. The desired structure is as follows: Slide datapoint 1 datapoint 2 datapoint 3 datapoint 4 datapoint 5 datapoint 6 datapoint 7 ...

JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log. Here is the code snippet: this.logicItem.$promise.then( ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Seamless scrolling experience achieved after implementing a header that appears when scrolling up

My goal is to create a header with the following functionalities: Initially displays with a transparent background Upon scrolling down the page by 25px, it will dynamically add the header--maroon class to the header, which alters the background color and ...

Tips for passing an array to a different function using Jquery

I need to pass an array to another function <div id="test"></div> <div id="test2"></div> <input type="button" value="chk" id="go" /> <script> $(function() { var c = 1; var i = 5; var dat ...

AngularJS is patiently waiting for the tag to be loaded into the DOM

I am trying to incorporate a Google chart using an Angular directive on a webpage and I want to add an attribute to the element that is created after it has loaded. What is the most effective way to ensure that the element exists before adding the attribut ...

Implementing TypeScript type definitions for decorator middleware strategies

Node middlewares across various frameworks are something I am currently pondering. These middlewares typically enhance a request or response object by adding properties that can be utilized by subsequent registered middlewares. However, a disadvantage of ...

Trouble with displaying PHP and AJAX call after switching from JS fetch

Initially, I had a JavaScript function set up to retrieve Wikipedia articles for the chosen country. The code was originally sourced from JS Fiddle and it worked flawlessly. However, I have now been informed that my course mandates all API calls to be made ...

Disable the mouseenter event in jQuery when the window is resized

I am facing a challenge with my code. I have two different functions that are triggered based on the screen size - one for desktop and one for mobile. The issue arises when transitioning from a desktop to a mobile view, as the hover/mouseenter effect still ...

Display a loading screen while retrieving information in React Redux

I have two sections on the page - a collection of IDs on the left side and data display on the right. When the page loads for the first time, all data related to every ID is shown. However, users can only select one ID at a time to view its specific data. ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

What is the best way to seamlessly move an element from a margin-left position of -9999px back onto the page?

Here are some additional details - because of unusual restrictions with the YouTube API, I have to push a container off the page in order to create the illusion that the container is hidden. I accomplish this using the following CSS class: .my_hide{ ...

The functionality of Bootstrap tabs is compromised when used within a modal dialog

I am encountering an issue while using Django and Bootstrap to implement nav-tabs within a modal that is displayed upon clicking a button. The problem lies in the fact that when a tab is clicked, its content does not appear. Below is a basic example: {% ...

How come my React application is not fetching the latest version of the state variables?

Currently, I am actively engaged in developing a software application that retrieves an SVG file and transforms it into a collection of React components with customized interactive features. The obstacle I am encountering pertains to the onClick function ...

What is the best method for clearing form validation when using a create modal?

I'm facing a dilemma in this situation. Whenever I click on + Rule, it triggers the function below: showAddRuleModal() { this.showAddRule = true this.$refs.form.reset() //reset form values this.ruleName = '' this.url = ...