Search code examples
javascripterror-handlingsyntax-error

JavaScript SyntaxError is just a string, not an object?


My application is dynamically loading scripts, so I set a window.onerror handler to report syntax errors that prevent the scripts loading, as follows:

window.onerror = function(error) {
  alert("ERROR: " + error.message + ": " + error.stack);
};

What I get when I load a script is an alert saying ERROR: undefined: undefined. When I change it to display the value and type of error:

window.onerror = function(error) {
  alert("ERROR: " + typeof(error) + ": " + error);
};

what I get is ERROR: string: SyntaxError: missing ) after argument list. This happens on both Firefox and Chrome.

According to the docs, SyntaxError is supposed to be an Error object with message and stack and other properties. I'd really like to know where the error occurred, and not just what it is! Am I doing something wrong here? Is there any way I can get more information about the error?


Solution

  • The error event has multiple parameters. The first is the event name, which is a string.

    onerror = (event, source, lineno, colno, error) => {};
    

    Docs