2

I'm looking for a way of handling errors with the native javascript fetch api. Used to use jQuery, but I'm trying to use more native javascript functions.

I found this blog and like the approach: https://learnwithparam.com/blog/how-to-handle-fetch-errors/

fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } 

    throw Error(response.statusText);
    
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });

However, in the catch I'm getting the statusText that belongs to the HTTP code. For 400 for example Bad request. But that is not wat I want, my call to the server will respond with exactly what is wrong. So I want to use the response body text as a the error. I tried different ways, but I can't get the response body incase the HTTP code is 400. With jQuery I used response.responseJSON.html. But this is not available with the fetch api.

So how can I can use the response body as error code.

8
  • What does response.statusText return? Commented Jan 19, 2022 at 14:35
  • In case of 400, Bad request. If 401 Unauthorized. See developer.mozilla.org/en-US/docs/Web/HTTP/Status Commented Jan 19, 2022 at 14:36
  • I thought that it was the message from the server. So could you look for your message in the response's body. It should be there and you could use throw Error(response.message). Commented Jan 19, 2022 at 14:39
  • No, if I console.log(response) I can't find my response body. Commented Jan 19, 2022 at 14:43
  • @Timo002 What if you try response.text().then(console.log); - does that display the correct error message? Commented Jan 19, 2022 at 15:21

1 Answer 1

10

The fetch API was designed to work best with async functions. If you can make your outer function async, your code would become:

try {
  const response = await fetch(url);
  if (!response.ok) {
    const text = await response.text();
    throw Error(text);
  }
  
  const jsonResponse = await response.json();
  // do whatever you want with the JSON response
    
} catch (error) {
  console.log(error);
}

Otherwise, it gets a bit more complicated:

fetch(url)
  .then((response) => {
    if (response.ok) {
      return response.json();
    }
    
    return response.text().then((text) => throw Error(text));
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });
Sign up to request clarification or add additional context in comments.

1 Comment

This is great! Best answer online :) I've been looking for a way to show my JSON error message that came back from Node.js so I still to had to do response.json(); no matter what! async await solves it perfectly.

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.