Search code examples
javascriptpromisees6-promise

catch handler in promise chain not capturing the error


My code is a simple fetch example which works when the correct resource URL is provided. But when i misspell the resource name, i was expecting the error to be trapped in the catch block but that didnt happen. The console records an error "Failed to load resource: the server responded with a status of 404 (not found)

My code is


      fetch('coffee.jpg')
                .then(response => response.blob())
                .then(blob => {

                    let myURL =  URL.createObjectURL(blob);
                    let img = document.createElement('img');
                    img.src = myURL;
                    document.body.appendChild(img);

                })
                .catch(err => {
                  console.log(" Error fetching file -  " + err.message);
                });


Solution

  • You can add an error handler middleware like this:

    function handleErrors(response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }
    
    fetch('coffee.jpg')
      .then(handleErrors)
      .then(response => response.blob())
      .then(blob => {
    
        let myURL = URL.createObjectURL(blob);
        let img = document.createElement('img');
        img.src = myURL;
        document.body.appendChild(img);
    
      })
      .catch(err => {
        console.log(" Error fetching file -  " + err.message);
      });