javascriptjquerygetscript

Exception in external script not showing on console


I'm making a small library to be used on browser and came across (what I think of as) a strange behaviour of throw.

When I run this code:

var SomeClass = function() {};

SomeClass.prototype.error = function() {
    throw new Error('Error!');
};

var myInstance = new SomeClass();
myInstance.error();

it's just fine, SomeClass is defined internally and myInstance is initialized in the same script, and the exception is displayed on the browser's console. However:

// Code on a web page
var SomeClass = function() {};

SomeClass.prototype.error = function() {
    throw new Error('Error!');
};
// Initialize a SomeClass instance locally
$.getScript('http://127.0.0.1:5500/SomeClass.js')
.then(function() {
    var myInstance = new SomeClass();
    myInstance.error();
});

In this case nothing is shown on console. Why does this happen?

This can be prevented if we create an Error instance as a callback to console.error as in the following, but I don't know this is a good practice.

// Code on a web page
var SomeClass = function() {};

SomeClass.prototype.error = function() {
    throw console.error(new Error('Error!')); // console.error added
};

Any help would be appreciated.


Solution

  • It is because you are using a Promise (getScript). Inside a promise errors are throwed/pass to the catch function. So if you do like this it will work:

    var SomeClass = function () {};
    
    SomeClass.prototype.error = function () {
      throw new Error("Error!");
    };
    
    const myPromise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, 300);
    });
    
    myPromise
      .then(() => {
        let some = new SomeClass();
        console.log("execute");
        some.error();
      })
      .catch((e) => {
        console.log("catch error");
        console.log(e);
      });