jcalfee314
jcalfee314

Reputation: 4830

XMLHttpRequest detecting 404 (Not Found)

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).

Upvotes: 5

Views: 14380

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

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

Upvotes: 7

Daan Wilmer
Daan Wilmer

Reputation: 955

Using https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-status:

XmlHttpRequest objects (you have one in the variable xhr) have a read-only property status that you can use to get the status text once it's loaded.

Upvotes: 0

Related Questions