Search code examples
javascripterror-handlingreferenceerror

How to catch an "ReferenceError" with "onerror"


I want my script to check many dependencies, and on success a submit button should appear. BUT if there was any kind of javascript error, the button should never appear. So I want to do at the end of my script something like:

if (typeof window.error_has_appeared == 'undefined') {
    button.classList.add("button_activated");
}

I have tried to solve my issue with window.onerror, but it seems not to catch all errors.

<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
   alert("ERROR");
};

window.onload = async function() {
   test
};
</script>

I can see in the javascript log: "ReferenceError: test is not defined". But why does the onerror alert not work?


Solution

  • Because you've made your onload handler an async function, so rather than being an unhandled error handled by the global error handler, the ReferenceError is an unhandled promise rejection, and so it's handled by the global promise rejection handler.

    Since the load event code doesn't do anything with the promise returned by an async function, just make your function not async:

    window.onerror = function(msg, url, line, col, error) {
       console.log("ERROR");
    };
    
    window.onload = function() {
       test
    };

    Or use onunhandledrejection:

    window.onerror = function(msg, url, line, col, error) {
       console.log("onerror triggered");
    };
    window.onunhandledrejection = function(msg, url, line, col, error) {
       console.log("onunhandledrejection triggered");
    };
    
    window.onload = async function() {
       test
    };