Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest detecting 404 (Not Found)

Tags:

javascript

If the URL is correct (file.dat exists), this works great (the file length matches). If it is wrong I will see a very small file length and I will not see the xhr.onerror.

How can I detect that the URL was incorrect?

var xhr = new XMLHttpRequest()
xhr.responseType = "blob"
xhr.onload = ()=> {
    var reader = new FileReader()
    reader.onload = evt => {
        var contents = new Buffer(evt.target.result, 'binary')
        console.log('file len',contents.length) 
    }
    reader.readAsBinaryString(xhr.response)
}
xhr.addEventListener("error", () => { console.error('xhr.onerror',e) })
xhr.open("GET", "file.dat")
xhr.send()

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

I do see a stacktrace in the console pointing to xhr.send() GET http://localhost:8080/file.dat 404 (Not Found)

A try catch around both open and send does not catch any exceptions.

Files are served by WebpackDevServer (I hope that should not matter though).

like image 418
jcalfee314 Avatar asked Oct 23 '15 18:10

jcalfee314


1 Answers

You can check the status of the response object.

// Not using arrow function because I don't want the lexical `this`
xhr.onload = function() {
    if (this.status === 404) {
       // not found, add some error handling
       return;
    }
    var reader = new FileReader()
    reader.onload = evt => {
        var contents = new Buffer(evt.target.result, 'binary')
        console.log('file len',contents.length) 
    }
    reader.readAsBinaryString(xhr.response)
}

Credit to https://developer.appcelerator.com/question/129410/xhr-request-cant-check-for-error-for-404-page-or-other-errors

like image 199
Juan Mendes Avatar answered Sep 23 '22 10:09

Juan Mendes