David
David

Reputation: 816

Retrieve the React Fetch Error Text for Different Error Results

So, I am fetching a url and my API returns either the data or a 500 error with a few error codes. I am trying to capture the error code and display it in React. In the console, I see the error, but it looks like this:

Error Image in Console

So, I see the 'Not Found' which is the text I want to display, but how do I get this text out of the error format so I can use it elsewhere?

Here is my code, hopefully this make sense what I am trying to do:

callApi = async (url) => {
    const response = await fetch(url);
    const body = await response.json();

    if (response.status !== 200) throw Error(body.messages);

    return body;
};

this.callApi(url)
  .then(results => {
      this.function(results);
  })
  .catch(err => {
      console.log(err);
      
      if (err === "Not Found") {
          console.log('Not Found')
      }
      
      if (err === "No Access") {
          console.log('No Access')
      }
  });

Upvotes: 0

Views: 346

Answers (1)

Matthew Herbst
Matthew Herbst

Reputation: 31973

JavaScript errors inherit from the base Error object. This means they will almost always have a set message property, meaning you can simply do:

console.log(err.message);

Also to be clear, fetch is a browser API, and has nothing to do with React.

Upvotes: 1

Related Questions