0

I am learning fetch API . I am trying to display a some text content from text file in my div element . I purposely misspelt my file name so to check if error is handled or not .Here is my update functio to display

function updateDisplay() {
  const path = "file.txt";
  
    fetch(path).then((response)=>{
      
      response.text().then((text)=>{
        mydiv.textContent =text;
      })
    
  }).catch((error)=>{
    console.log("there is error in fetching" + error);
  });
  
}

when file name is correct data is displayed correctly as expected. But when provide nonexistent file path the control is not reaching to catch block. On console i see

GET http://127.0.0.1/javascript/files.txt" 404 (Not Found)

But Biggest problem is content updated in my div element ,its all raw html response code.

I tried try catch around entire function but still the catch block is not triggering Tried multiple browser. same error.

  • 1
    This is because even a 404 response is not considered an error to be caught by the catch block, rather, it passes to the "then" function. If you want to test for 404, write something like this. .then(function(response) { if (response.status == 200) { console.log("file exists!"); } else { console.log("file doesn't exist!"); } – Yossi Sternlicht Dec 15 '20 at 14:17
  • Isn't 404 a valid response that should be handled in the "success" case? You get a valid response from the server therefore you should not enter the catch block. You might want to check this link for details: https://stackoverflow.com/a/39297738/14201528 – secan Dec 15 '20 at 14:18

0 Answers0