How to reject promise and catch the error if status is not OK with fetch and JavaScript?

Sometimes, we want to reject promise and catch the error if status is not OK with fetch and JavaScript.

In this article, we’ll look at how to reject promise and catch the error if status is not OK with fetch and JavaScript.

How to reject promise and catch the error if status is not OK with fetch and JavaScript?

To reject promise and catch the error if status is not OK with fetch and JavaScript, we can check the response.ok property.

For instance, we write

const response = await fetch(url);
if (response.ok) {
  return response.json();
} else {
  throw new Error("Something went wrong");
}

to make a get request to url by calling fetch with url.

Then we check if response.ok with true from the promise returned.

If it is, then we return response body returned by response.json

Otherwise, we throw an error.

This code should be in an async function.

Conclusion

To reject promise and catch the error if status is not OK with fetch and JavaScript, we can check the response.ok property.