Reputation: 115
I looked everywhere but I couldn't find something that helped. This has been really annoying me because I actually tested what I was doing a few weeks ago and it worked then.
So here's my code:
var error_handler = function(e) {
console.error(e);
e.preventDefault();
}
window.addEventListener('error', error_handler);
And that works for handling errors, but it's not handling errors like this:
Failed to load resource: the server responded with a status of 404 ()
when I wrote the code before, it did pick up those errors. Any idea what I'm doing wrong here?
Upvotes: 3
Views: 2104
Reputation: 3164
Actually, error
event does work for resource loading errors, you just need to set useCaputure
to true
window.addEventListener("error", (event) => {
console.log('error: ', event);
}, true);
You will not get the status code or text of the network response, but you will have an event that shows you the target that throws the error. For example:
> error: Event {isTrusted: true, type: 'error', target: img, currentTarget: Window, eventPhase: 1, …}
Upvotes: 2
Reputation: 1014
When a resource (such as an <img>
or <script>
) fails to load, an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but can be handled with a EventTarget.addEventListener
configured with useCapture
set to true
.
For more details refer this documentation
Upvotes: 2
Reputation: 207511
Loading an external file is not a JavaScript error so it is not going to be caught unless the error comes from the script file from trying to be executed. You can add an error event to the script tag, but you are not going to get the error message from it.
function handleError(evt){
console.log(evt);
}
var scr = document.createElement("script");
scr.src="error.js";
scr.onerror = handleError
document.body.appendChild(scr);
Upvotes: 0