title: Handling failed HTTP responses with fetch and async/await
body: <p>I use this code to handle failed requests with fetch (by throwing Error):</p>
  
  <pre><code>function asyncCall() {
      fetch("https://httpstat.us/500")
      .then(function(response) {
          if (!response.ok) {
              throw Error(response.statusText);
          }
          return response.text(); // or .json();
      })
      .then(function(text) {
          console.log("ok", text);
      }).catch(function(error) {
          console.log("error", error); 
      })
  
  }
  
  asyncCall();
  </code></pre>
  
  <p>Now I am interested on how async/await version of this code could look like, and this what I came with:</p>
  
  <pre><code>async function syncCall() {
    let response = await fetch("https://httpstat.us/200")
    if (response.ok) return await response.text()
    throw new Error(response.statusText)
  }
  
  async function callFetch() {
    try {
        let text = await syncCall()
        console.log(text)
    } catch(e) {
        console.log("error", e); 
    }
  }
  
  callFetch()
  </code></pre>
  
  <p>Is this code good, is there some nicer, shorter way?</p>