Home | History | Annotate | Download | only in js
      1 // Copyright 2014 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 'use strict';
      6 
      7 /**
      8  * This variable is checked in SelectFileDialogExtensionBrowserTest.
      9  * @type {number}
     10  */
     11 window.JSErrorCount = 0;
     12 
     13 /**
     14  * Counts uncaught exceptions.
     15  */
     16 window.onerror = function() { window.JSErrorCount++; };
     17 
     18 /**
     19  * Wraps the function to use it as a callback.
     20  * This does:
     21  *  - Capture the stack trace in case of error.
     22  *  - Bind this object
     23  *
     24  * @param {Object} thisObject Object to be used as this.
     25  * @param {...} var_args Arguments to be bound with the wrapped function.
     26  * @return {function} Wrapped function.
     27  */
     28 Function.prototype.wrap = function(thisObject, var_args) {
     29   var func = this;
     30   var liveStack = (new Error('Stack trace before async call')).stack;
     31   if (thisObject === undefined)
     32     thisObject = null;
     33   var boundArguments = Array.prototype.slice.call(arguments, 1);
     34 
     35   return function wrappedCallback(var_args) {
     36     try {
     37       var args = boundArguments.concat(Array.prototype.slice.call(arguments));
     38       return func.apply(thisObject, args);
     39     } catch (e) {
     40       // Some async function doesn't handle exception correctly. So outputting
     41       // the exception message and stack trace just in case.
     42       // The message will show twice if the caller handles exception correctly.
     43       console.error(e.stack);
     44       console.info('Exception above happened in callback.', liveStack);
     45 
     46       window.JSErrorCount++;
     47       throw e;
     48     }
     49   }
     50 };
     51