Search code examples
javascriptfetch

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.


Solution

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