title: Javascript fetch api use custom error message
body: <p>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.</p>
  <p>I found this blog and like the approach: <a href="https://learnwithparam.com/blog/how-to-handle-fetch-errors/" rel="nofollow noreferrer">https://learnwithparam.com/blog/how-to-handle-fetch-errors/</a></p>
  <pre><code>fetch(url)
    .then((response) =&gt; {
      if (response.status &gt;= 200 &amp;&amp; response.status &lt;= 299) {
        return response.json();
      } 
  
      throw Error(response.statusText);
      
    })
    .then((jsonResponse) =&gt; {
      // do whatever you want with the JSON response
    }).catch((error) =&gt; {
      // Handle the error
      console.log(error);
    });
  </code></pre>
  <p>However, in the catch I'm getting the statusText that belongs to the HTTP code. For 400 for example <code>Bad request</code>. 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 <code>response.responseJSON.html</code>. But this is not available with the fetch api.</p>
  <p>So how can I can use the response body as error code.</p>