0

I've been looking for this over and over but cant find the proper answer

Using Fetch, in order to throw errors when getting status other than ok we must do it manually. The back end is providing with an specific message about the error along the 401,404 etc, error code. I want to access to it on my fetch but dont know how.

            .then((response) => {
                if (response.ok) {
                    return response.text();
                }
                else {
                    throw new Error(response.text()); ///THIS DOES NOT WORK. 
                }
            })
            .then(result => alert ("Added Successfully"))
            .catch(error =>alert (error.message)); ///AND OF COURSE NEITHER DOES THIS.
2
  • try console.log(error) to see how the error looks like first, then you can specify the properties you want to access directly Commented Aug 20, 2020 at 12:14
  • thanks for your reply! console.log(error) bring Error: [object Promise] Commented Aug 20, 2020 at 13:31

1 Answer 1

0

You should console log your response and see what it contains. You also have to access the response object like this: response.text. You access it like its a function. You probably also have to parse the response before you access anything. Even though you didnt post the content of the response, the following snippet should point you into the right direction.

Check the snippet below which shows you a successfull error handling.

fetch("http://httpstat.us/404")
  .then( response => {
    if (!response.ok) {
      throw new Error(response)
    }
    return response.json() 
  })
  .catch( err => {
    console.log(err.message);
  })

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for yor reply. When I run this, the console.log brings [object Promise] not the actual message?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.