Is there a way for me to obtain the full error message after a failed fetch request?

I'm trying to capture all errors from the fetch function, including the specific red highlighted details as a string: https://i.sstatic.net/GtHxv.png

But when I catch an error in my code, all I get is "Failed to fetch." Here's what my code looks like:

try {
  response = await fetch(url, {
    method: method,
    body: JSON.stringify(payload),
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`RESPONSE NOT OK: ${response.status}`);
  }

  console.info('got 200 json response:' + (await response?.json()));
} catch (e) {
  console.error('CATCH BLOCK:' + e.message); // only gives me "Failed to fetch"
}

So, how can I retrieve the complete error message from the fetch request in a string format so that it can be displayed directly on my web interface?

Update

Just to clarify, I already know how to solve the error itself. This question focuses solely on extracting the full error message as a string.

Answer №1

It's important to note that there are actually two separate requests happening, not just one, which can lead to confusion. Preflight requests are automatically generated by your browser and occur independently of your code. The purpose of logging them in the console is solely for developer visibility. Your fetch request does not directly interact with these preflight requests.

If you want to delve into this topic further, check out this specific question.

Although a preflight request won't provide insight into the initial failed request, you do have the ability to trigger one manually by executing an OPTIONS request like so:

OPTIONS /resource/foo
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: origin, x-requested-with
Origin: https://foo.bar.org

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

What causes a React Ref callback to be invoked multiple times during the initial loading of a page?

To find more information, please visit this URL within the React DOCS. You can also access a version of this code here. I acknowledge that it is recommended to use the useCallback hook in a Functional React Component to create a ref callback according to ...

The Laravel Mix Hot Module Replacement (HMR) server fails to start up

Laravel Mix Version: 6.0.43 Node Version (node -v): 16.13.1 NPM Version (npm -v): 8.1.2 OS: Windows 10 21h2 Description: Encountering an issue on a fresh installation of Laravel and other existing projects. When running npm run hot, the script tag sourc ...

A guide on using Jest.js to test labels within Vue 3 Quasar components by utilizing a forEach loop

Within my Vue Quasar component, a badge is implemented as shown below: <q-badge :color="green" text-color="white" :label="`${value.toFixed(2)}%`" /> The corresponding script is structured like this: <scri ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: https://i.sstatic.net/RL3w4.gif I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for th ...

Submitting forms with Ajax without reloading the page can cause errors in Internet Explorer

Simply put: Upon clicking the login button in Firefox, Chrome, or Safari, the form is submitted correctly, running a validation via ajax and opening a new page. However, in Internet Explorer (version less than 9), the submission attempts to post to the c ...

Passing an array list back to the parent component in ag-grid(Vue) - A step-by-step guide

Currently, I am integrating AG Grid with Vue. My project has a specific requirement where two checkboxes are displayed using a cellRendererFramework. However, I am facing difficulties in fetching the values of these checkboxes from the row definitions. The ...

AngularJS Event Handler Fails to Trigger

I'm currently working on a form that I need to submit using the ng-submit event through a custom Auth service. This is a snippet of the login.html (partial template) <div class='container'> <form class='form-signin' ...

Receiving a "Bad Request" error when trying to access a website

Every time I attempt to call a lengthy URL, I encounter a Bad Request issue. https://localhost:44320/RespostaEmail/96635/750396/[%7B%22IdItem%22:8,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:1,%22IdTipoReposta%22:80%7D,%7B%22IdItem%22:3,%22IdTipoReposta%22:8 ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Transforming HTML into a Console Experience (Angular 16)

I'm experimenting with creating a console/CLI style experience using HTML. The goal is to have the input fixed at the bottom of the window, while commands and output rise up from the bottom and eventually disappear off the top of the screen, enabling ...

Creating a progress bar for file uploads without using jQuery

We're currently seeking a way to implement a file upload progress bar feature without relying on ajax or jQuery. Unfortunately, we haven't come across any helpful tutorials through our Google searches. Below is the basic code snippet we have so ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

Ways to transfer certain characteristics of an Observable to a different Observable by leveraging RxJS operators

I am working with two Observables, employee$ and personalInformation$. The personalInformation$ Observable is a subset of employee$ and I need to map the matching properties from employee$ to personalInformation$. Although both observables have many more f ...

Typescript Support in Goland IDE for HTML Documents

I'm currently utilizing Go for my programming tasks, and I prefer the Goland IDE developed by Jetbrains. Is there a way for me to incorporate typescript into my .html template files that contain a mix of HTML, CSS, and JS? Your assistance is much ap ...

Having trouble with the startWith operator in RxJS? It seems like it's

Recently, I decided to delve into the world of Observables and reactive programming with rxjs. To get started, I integrated the redux-observable library into my react/redux application. One of the first things I did was create an epic specifically for the ...

Limiting the number of checkboxes selected in a Checkbox Group based on

I am working on a checkboxGroupInput that has 4 options (denoted as A, B, C, D). My goal is to restrict the selection to only 2 choices. The user should be able to pick a 3rd option. In this scenario, only the newly selected (3rd) and previously selec ...

Substitute Symbolic Codes in an Object with Written Text

Here's the structure of the object: { where: { [Symbol(or)]: [ [Object], [Object] ] },hooks: true, rejectOnEmpty: false } When I use JSON.stringify on it, the result is: {"where":{},"hooks":true,"rejectOnEmpty":false} T ...

Tips for comparing two arrays in node.js

I am faced with the task of comparing two arrays. let runArray = ['Welcome', 'Hello'] let data = [{ Node:'Good', Session:'2', Run:'Welcome', Run_Group:'Display', Elapsed_Ms: '1000& ...

How can I eliminate text using regular expressions?

Greetings, I am seeking assistance with content removal using regular expressions. Below is the regular expression code I have written: reg = reg.replace(/\|.*?(\|)/g, ''); Input: One-1|two-2|Three-3|Four-4|Five-5 Six-6|Seven-7|Eig ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...