Reputation: 4830
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
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)
}
Upvotes: 7
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