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 */
11window.JSErrorCount = 0;
12
13/**
14 * Count uncaught exceptions.
15 */
16window.onerror = function() { window.JSErrorCount++; };
17
18// Overrides console.error() to count errors.
19/**
20 * @param {...Object} var_args Message to be logged.
21 */
22console.error = (function() {
23  var orig = console.error;
24  return function() {
25    window.JSErrorCount++;
26    return orig.apply(this, arguments);
27  };
28})();
29
30// Overrides console.assert() to count errors.
31/**
32 * @param {boolean} condition If false, log a message and stack trace.
33 * @param {...Object} var_args Objects to.
34 */
35console.assert = (function() {
36  var orig = console.assert;
37  return function(condition) {
38    if (!condition)
39      window.JSErrorCount++;
40    return orig.apply(this, arguments);
41  };
42})();
43
44/**
45 * Wraps the function to use it as a callback.
46 * This does:
47 *  - Capture the stack trace in case of error.
48 *  - Bind this object
49 *
50 * @param {Object} thisObject Object to be used as this.
51 * @return {function} Wrapped function.
52 */
53Function.prototype.wrap = function(thisObject) {
54  var func = this;
55  var liveStack = (new Error('Stack trace before async call')).stack;
56  if (thisObject === undefined)
57    thisObject = null;
58
59  return function wrappedCallback() {
60    try {
61      return func.apply(thisObject, arguments);
62    } catch (e) {
63      console.error('Exception happens in callback.', liveStack);
64
65      window.JSErrorCount++;
66      throw e;
67    }
68  }
69};
70