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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With