UNPKG

2.9 kBJavaScriptView Raw
1/*
2 * Copyright 2012 Amadeus s.a.s.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16(function () {
17 var window = this;
18
19 var emptySpaceStart = /^\s*/;
20 var emptySpaceEnd = /\s*$/;
21
22 var startsWithAt = /^\s*at\s+/;
23 var phantomJsStackWithFunctionName = /^\s*at\s+([^(]+)\((.*):([0-9]+)\)$/;
24 var phantomJsStackWithoutFunctionName = /^\s*at\s+(.*):([0-9]+)$/;
25 var firefoxStack = /^([^@]*)@(.*):([0-9]+)$/;
26
27 var processLine = function (line) {
28 var match = phantomJsStackWithFunctionName.exec(line);
29 if (match) {
30 return {
31 'function': match[1],
32 'file': match[2],
33 'line': match[3]
34 };
35 }
36 match = phantomJsStackWithoutFunctionName.exec(line);
37 if (match) {
38 return {
39 'function': '',
40 'file': match[1],
41 'line': match[2]
42 };
43 }
44 match = firefoxStack.exec(line);
45 if (match) {
46 return {
47 'function': match[1],
48 'file': match[2],
49 'line': match[3]
50 };
51 }
52 return {
53 'function': line
54 };
55 };
56
57 window.attester.stackTrace = function (exception) {
58 var skipFirstLine = false;
59 if (!exception || !exception.stack) {
60 try {
61 var zero = 0;
62 zero(); // raise an exception on purpose to have the stack trace
63 } catch (e) {
64 exception = e;
65 skipFirstLine = true;
66 }
67 }
68 var res = [];
69 var stack = exception.stack;
70 if (stack) {
71 // remove extra space at the end and begining of the stack:
72 stack = stack.replace(emptySpaceStart, '').replace(emptySpaceEnd, '');
73 res = stack.split('\n');
74 if (res.length >= 2 && startsWithAt.test(res[1]) && !startsWithAt.test(res[0])) {
75 // PhantomJS (and perhaps other browsers) include the error message in the stack trace
76 // we remove it here:
77 res.splice(0, 1);
78 }
79 if (skipFirstLine) {
80 res.splice(0, 1);
81 }
82 for (var i = 0, l = res.length; i < l; i++) {
83 res[i] = processLine(res[i]);
84 }
85 }
86 return res;
87 };
88
89})();