admin管理员组

文章数量:1289421

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: /

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.

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./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.

Share Improve this question asked Jan 19, 2022 at 14:19 Timo002Timo002 3,2086 gold badges42 silver badges70 bronze badges 8
  • What does response.statusText return? – AchoVasilev Commented Jan 19, 2022 at 14:35
  • In case of 400, Bad request. If 401 Unauthorized. See developer.mozilla/en-US/docs/Web/HTTP/Status – Timo002 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). – AchoVasilev Commented Jan 19, 2022 at 14:39
  • No, if I console.log(response) I can't find my response body. – Timo002 Commented Jan 19, 2022 at 14:43
  • @Timo002 What if you try response.text().then(console.log); - does that display the correct error message? – Richard Deeming Commented Jan 19, 2022 at 15:21
 |  Show 3 more ments

1 Answer 1

Reset to default 10

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

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 plicated:

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);
  });

本文标签: Javascript fetch api use custom error messageStack Overflow