Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript fetch api use custom error message

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.

like image 594
Timo002 Avatar asked Feb 01 '26 02:02

Timo002


1 Answers

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);
  });
like image 162
Richard Deeming Avatar answered Feb 02 '26 15:02

Richard Deeming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!