How to handle error status in ES6 Promises?

promise then catch/finally
promise catch
try/catch promise
promise reject catch
promise then after catch
throw error in promise chain
promise catch rethrow
javascript promise

I am using ES6 and trying to handle error status of the fetch() result.

I know I can catch error like this:

fetch(`http://${this.serverAddress}/reset`)
        .then((resp) => {
            Logger.debug(JSON.stringify(resp));
        })
        .catch((err) => {
            Logger.debug(JSON.stringify(err));
        });

In catch block I take an Error with message "Failed to fetch". There is no status information.

I have found the following suggestion:

fetch('/some/url/')
  .then(processResponse)
  .then(response => {
    // do something
  })
  .catch(response => {
    // repsonses with status >= 400 get rejected. you can access response.status and response.data here too
    if (response.status === 400) {
        // handle form validation errors, response.data.errors...
    } else if (response.status === 403) {
        // handle permission errors
    } // etc
  });

But response.status is undefined in catch block.

How can I get status code of the error to handle it?

UPDATE:

Thank you for the responces. Please see my updates:

My actual token looks as http://api.service/v2/prices/latest?token=err. If I write my token instead of err, then it works. When I try this URL, my code go to the catch block, not then.

I noticed the following error in browser console:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I add {mode: "no-cors"}, code go to the then, but status is always 0. This is not that I want.

I tried to add

mode: "cors",
headers: {
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json"
    }

This is not help, I still have No 'Access-Control-Allow-Origin' header error.

You may try to handle the error status by throwing error during response processing right after the fetch is done with !ok:

fetch('/some/url/')
  .then(response => {
    if (!response.ok) {
      throw Error({ status: response.status });
    }
    response.json();
  })
  .then(response => {
    // do something
  })
  .catch(error => {
    switch(error.status) {
      // ...
    }
  });

JavaScript Promises and Error Handling, JavaScript skills up to date, you've probably come across ES6 Promises before​. The standard way to handle errors from promises is to add a catch handler exceptions, not unexpected errors caused by bugs in the code. If you’ve kept your JavaScript skills up to date, you’ve probably come across ES6 Promises before. Promises provide a clean, flexible way to chain multiple async operations together without having to nest function calls inside callbacks (which might lead to callback hell). Promises can be powerful but if you don’t follow proper error-handling practices, they can make life difficult.

You can't check the status in code.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

Basically, fetch() will only reject a promise if a networking error occurs.

The fetch API provides a simple ok flag that indicates whether an HTTP response’s status code is in the successful range or not. See the below example

fetch("http://httpstat.us/500")
    .then(function(res) {
        if (!res.ok) {
            throw Error(res.statusText);
        }
        return res;
    }).then(function(res) {
        console.log("ok");
    }).catch(function(error) {
        console.log(error);
    });

Handling Errors with ES6, Instead, we're handling our errors with ES6 features (mainly promises and classes). As the person writing the code, you always want to make sure you know  Instead, we’re handling our errors with ES6 features (mainly promises and classes). In this post, I’ll talk about why we’ve made this transition. Handling Errors with ES6 - Runnablog

After the fetch request check if response is as expected. If not, throw new error with a custom message. In the catch check if this custom message is there for the thrown error. Handle accordingly. You can also create custom Errors and check the same.

Promise.prototype.catch(), JS allows error handling with the help of try, catch, and throw. const main This little addition of async/await in your code does two things — But if any of the promises above rejects (a network problem or invalid json or whatever), then it would catch it. Implicit try…catch. The code of a promise executor and promise handlers has an "invisible try..catch" around it. If an exception happens, it gets caught and treated as a rejection. For instance, this code:

As seen in the docs the catch block will be reached only if the request didn't complete. When there is a status code available (and all the other data is received as well) fetch will resolve and therefore the then block will be reached.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. - Source

So all you have to do is logging resp.status instead of resp.

fetch(`http://${this.serverAddress}/reset`)
  .then((resp) => {
    Logger.debug(JSON.stringify(resp.status));
  })
  .catch((err) => {
    Logger.debug(JSON.stringify(err));
});

In catch block I take an Error with message "Failed to fetch". There is no status information.

So in case the catch block is getting called the request didn't even finish. This might be caused because you are not using options like method, headers,... If needed, which one and what values depends on the backend you are using.

JavaScript: Error handling with Promises and Async/Await, an error thrown inside the promise, triggers .catch() function example() failing to catch a reject means the code will continue to execute // as if  I'm trying to lint a codebase that contains ES6 (on the server) as well as ES5 (on the client). I'm running into problems as ES6 will ship Promises by default but ES5 won't.

JavaScript Promises and Errors, There are different ways to build error handling into your code, including the neat, built-in “try… catch” paradigm. The basic syntax looks like this: try { // code that  Teaches it how to yield promises (through Promise.coroutine) Returns a normal Express route function When this function executes, it will call the coroutine, catch any errors, and pass them to next .

Using .then(), .catch(), .finally() to Handle Errors in Javascript Promises, You may try to handle the error status by throwing error during response processing right after the fetch is done with !ok : fetch('/some/url/')  When promises and tasks collide. If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally.

How to handle error status in ES6 Promises?, When dealing with asynchronous code, JavaScript's ES6 promises can make your life a lot easier. No more callback pyramids, no more error  Promise.all takes an array of promises and creates a promise that fulfills when all of them successfully complete. You get an array of results (whatever the promises fulfilled to) in the same order as the promises you passed in.

Comments
  • You should do that checking in processResponse, which has access to the response object (and you can return Promise.reject(...) with whatever you want)
  • It is possible to check the status code. Though not within the catch block but in the then block.