Requirejs combined application window.onerror error handling

439 views Asked by At

In a Backbone and requirejs 2x based application, only when the application is combined through grunt-contrib-require, window.onerror stops trapping errors.

The window.onerror function id declared before and outside the Backbone application and send errors to a backend.

Sorry, cannot post much of the application but those interested parts

this is my app/main.js file

require(["config"], function () {

    // config is a require.config({}); definition

    require(["app", "router"], function (app, Router) {
        app.initialize(new Router());
    });

});

Gruntfile.js section regarding requirejs task

    requirejs : {
        debug : {
            options : {
                mainConfigFile : "app/config.js",
                generateSourceMaps : false,
                include : [ "main" ],
                insertRequire : [ "main" ],
                out : "app.combined.js",
                optimize : "none",
                findNestedDependencies : true,
                name : "config",
                baseUrl : "app",
                wrap : false,
                preserveLicenseComments : false
            }
        }
    }

Embed of the not combined application:

<script>
  window.onerror = function(msg, url, line, colno, error) {
     console.debug('onerror',arguments);
     // data will be sent to backend

     // TRACE FIRED

  }
</script>

<script src="require.js" data-main="app/main"></script>

Embed of the combined application:

<script>
  window.onerror = function(msg, url, line, colno, error) {
     console.debug('onerror',arguments);
     // data will be sent to backend

     // TRACE NOT FIRED
  }
</script>
<script src="app.combined.js" ></script>

any suggestion welcome! thank you.

1

There are 1 answers

0
mattimatti On

I found out a solution to this.

I should declare the window.onerror after window load.

    $(window).load(function() {

      window.onerror = function(msg, url, line, colno, error) {

        console.debug('onerror',arguments);

        // data will be sent to backend

        // TRACE FIRED
     };
    });

    <script src="app.combined.js" ></script>