1 | var pkg = require('../package.json');
|
2 |
|
3 | var fs = require('fs');
|
4 | var os = require('os');
|
5 | var EventEmitter = require('events').EventEmitter;
|
6 | var request = require('request');
|
7 | var stackTrace = require('stack-trace');
|
8 | var merge = require('lodash.merge');
|
9 | var execSync = require('child_process').execSync;
|
10 | var url = require('url');
|
11 |
|
12 | var truncator = require('../lib/truncator');
|
13 |
|
14 |
|
15 | var HTTP_STATUS_CODES = require('http').STATUS_CODES;
|
16 | var DEFAULT_SEVERITY = 'error';
|
17 |
|
18 |
|
19 | function Airbrake() {
|
20 | this.key = null;
|
21 | this.projectId = null;
|
22 |
|
23 | this.host = 'https://' + os.hostname();
|
24 | this.env = process.env.NODE_ENV || 'development';
|
25 | this.whiteListKeys = [];
|
26 | this.blackListKeys = [];
|
27 | this.filters = [];
|
28 | this.projectRoot = process.cwd();
|
29 | this.appVersion = null;
|
30 | this.timeout = 30 * 1000;
|
31 | this.consoleLogError = false;
|
32 |
|
33 | this.proxy = null;
|
34 | this.protocol = 'https';
|
35 | this.serviceHost = process.env.AIRBRAKE_SERVER || 'api.airbrake.io';
|
36 | this.requestOptions = {};
|
37 | this.ignoredExceptions = [];
|
38 | this.exclude = [
|
39 | 'type',
|
40 | 'message',
|
41 | 'arguments',
|
42 | 'stack',
|
43 | 'url',
|
44 | 'session',
|
45 | 'params',
|
46 | 'component',
|
47 | 'action',
|
48 | 'ua'
|
49 | ];
|
50 | }
|
51 |
|
52 | merge(Airbrake.prototype, EventEmitter.prototype);
|
53 |
|
54 | Airbrake.PACKAGE = (function() {
|
55 | var json = fs.readFileSync(__dirname + '/../package.json', 'utf8');
|
56 | return JSON.parse(json);
|
57 | }());
|
58 |
|
59 | Airbrake.createClient = function(projectId, key, env) {
|
60 | var instance = new this();
|
61 | instance.key = key;
|
62 | instance.env = env || instance.env;
|
63 | instance.projectId = projectId || instance.projectId;
|
64 |
|
65 | if (!instance.key || !instance.projectId) {
|
66 | throw new Error('Key or project ID missing during Airbrake.createClient()');
|
67 | }
|
68 |
|
69 | return instance;
|
70 | };
|
71 |
|
72 | Airbrake.prototype.expressHandler = function(disableUncaughtException) {
|
73 | var self = this;
|
74 |
|
75 | if (!disableUncaughtException) {
|
76 | process.on('uncaughtException', function(err) {
|
77 | self._onError(err, true);
|
78 | });
|
79 | }
|
80 |
|
81 | return function errorHandler(err, req, res, next) {
|
82 | var error = err;
|
83 | var requestObj = req;
|
84 | var responseObj = res;
|
85 |
|
86 | if (responseObj.statusCode < 400) responseObj.statusCode = 500;
|
87 |
|
88 | error.url = requestObj.url;
|
89 | error.action = requestObj.url;
|
90 | error.component = 'express';
|
91 | error.httpMethod = requestObj.method;
|
92 | error.params = requestObj.body;
|
93 | error.session = requestObj.session;
|
94 | error.ua = requestObj.get('User-Agent');
|
95 |
|
96 | self._onError(err, false);
|
97 | next(err);
|
98 | };
|
99 | };
|
100 |
|
101 | Airbrake.prototype.hapiHandler = function() {
|
102 | var self = this;
|
103 | var plugin = {
|
104 | register: function(server, options, next) {
|
105 | server.on('request-error', function(req, err) {
|
106 | var error = err;
|
107 |
|
108 | error.url =
|
109 | req.connection.info.protocol + '://' +
|
110 | req.info.host +
|
111 | req.url.path;
|
112 |
|
113 | error.action = req.url.path;
|
114 | error.component = 'hapi';
|
115 | error.httpMethod = req.method;
|
116 | error.params = request.params;
|
117 | error.ua = req.headers['user-agent'];
|
118 |
|
119 | self._onError(err, false);
|
120 | });
|
121 |
|
122 | next();
|
123 | }
|
124 | };
|
125 |
|
126 | plugin.register.attributes = { pkg: pkg };
|
127 | return plugin;
|
128 | };
|
129 |
|
130 | Airbrake.prototype._onError = function(err, die) {
|
131 | var self = this;
|
132 | var error = (err instanceof Error) ? err : new Error(err);
|
133 | self.log('Airbrake: Uncaught exception, sending notification for:');
|
134 | self.log(error.stack || error);
|
135 |
|
136 | self.notify(error, function(notifyErr, notifyUrl, devMode) {
|
137 | if (notifyErr) {
|
138 | self.log('Airbrake: Could not notify service.');
|
139 | self.log(notifyErr.stack);
|
140 | } else if (devMode) {
|
141 | self.log('Airbrake: Dev mode, did not send.');
|
142 | } else {
|
143 | self.log('Airbrake: Notified service: ' + notifyUrl);
|
144 | }
|
145 |
|
146 | if (die) {
|
147 | process.exit(1);
|
148 | }
|
149 | });
|
150 | };
|
151 |
|
152 | Airbrake.prototype.handleExceptions = function(die) {
|
153 | var self = this;
|
154 | var shouldDie = (typeof die === 'undefined') ? true : die;
|
155 | process.on('uncaughtException', function(err) {
|
156 | self._onError(err, shouldDie);
|
157 | });
|
158 | };
|
159 |
|
160 | Airbrake.prototype.log = function(str) {
|
161 | if (this.consoleLogError) {
|
162 | console.error(str);
|
163 | }
|
164 | };
|
165 |
|
166 | Airbrake.prototype._sendRequest = function(body, cb) {
|
167 | var callback = this._callback(cb);
|
168 |
|
169 | var options = merge({
|
170 | method: 'POST',
|
171 | url: this.url('/api/v3/projects/' + this.projectId + '/notices?key=' + this.key),
|
172 | body: body,
|
173 | timeout: this.timeout,
|
174 | headers: {
|
175 | 'Content-Length': body.length,
|
176 | 'Content-Type': 'application/json',
|
177 | Accept: 'application/json'
|
178 | }
|
179 | }, this.requestOptions);
|
180 |
|
181 | request(options, function(requestErr, res, responseBody) {
|
182 | if (requestErr) {
|
183 | return callback(requestErr);
|
184 | }
|
185 |
|
186 | if (typeof responseBody === 'undefined') {
|
187 | return callback(new Error('invalid body'));
|
188 | }
|
189 |
|
190 | if (res.statusCode >= 300) {
|
191 | var status = HTTP_STATUS_CODES[res.statusCode];
|
192 |
|
193 | var explanation = responseBody.match(/<error>([^<]+)/i);
|
194 | explanation = (explanation)
|
195 | ? ': ' + explanation[1]
|
196 | : ': ' + responseBody;
|
197 |
|
198 | return callback(new Error(
|
199 | 'Notification failed: ' + res.statusCode + ' ' + status + explanation
|
200 | ));
|
201 | }
|
202 |
|
203 | return callback(null, JSON.parse(responseBody).url);
|
204 | });
|
205 | };
|
206 |
|
207 | Airbrake.prototype.addFilter = function(filter) {
|
208 | this.filters.push(filter);
|
209 | };
|
210 |
|
211 | Airbrake.prototype.notify = function(err, cb) {
|
212 | var callback = this._callback(cb);
|
213 | var exit = false;
|
214 |
|
215 | this.ignoredExceptions.forEach(function(exception) {
|
216 | if (err instanceof exception) {
|
217 | exit = true;
|
218 | }
|
219 | });
|
220 |
|
221 | var notice = this.notifyJSON(err);
|
222 |
|
223 | this.filters.forEach(function(filter) {
|
224 | if (notice) {
|
225 | notice = filter(notice);
|
226 | }
|
227 | });
|
228 |
|
229 | if (exit || !notice) {
|
230 | return callback(null, null, false);
|
231 | }
|
232 |
|
233 | return this._sendRequest(truncator.jsonifyNotice(notice), callback);
|
234 | };
|
235 |
|
236 | Airbrake.prototype._callback = function(cb) {
|
237 | var self = this;
|
238 | return function(err) {
|
239 | if (cb) {
|
240 | cb.apply(self, arguments);
|
241 | return;
|
242 | }
|
243 |
|
244 | if (err) {
|
245 | self.emit('error', err);
|
246 | }
|
247 | };
|
248 | };
|
249 |
|
250 | Airbrake.prototype.url = function(path) {
|
251 | return this.protocol + '://' + this.serviceHost + path;
|
252 | };
|
253 |
|
254 | Airbrake.prototype.environmentJSON = function(err) {
|
255 | var cgiData = {};
|
256 | var self = this;
|
257 |
|
258 | if (this.whiteListKeys.length > 0) {
|
259 | Object.keys(process.env).forEach(function(key) {
|
260 | if (self.whiteListKeys.indexOf(key) > -1) {
|
261 | cgiData[key] = process.env[key];
|
262 | } else {
|
263 | cgiData[key] = '[FILTERED]';
|
264 | }
|
265 | });
|
266 | } else if (this.blackListKeys.length > 0) {
|
267 | Object.keys(process.env).forEach(function(key) {
|
268 | if (self.blackListKeys.indexOf(key) > -1) {
|
269 | cgiData[key] = '[FILTERED]';
|
270 | } else {
|
271 | cgiData[key] = process.env[key];
|
272 | }
|
273 | });
|
274 | }
|
275 |
|
276 | if (err.httpMethod) {
|
277 | cgiData.httpMethod = err.httpMethod;
|
278 | }
|
279 |
|
280 | Object.keys(err).forEach(function(key) {
|
281 | if (self.exclude.indexOf(key) >= 0) {
|
282 | return;
|
283 | }
|
284 |
|
285 | cgiData['err.' + key] = err[key];
|
286 | });
|
287 |
|
288 | cgiData['process.pid'] = process.pid;
|
289 |
|
290 | if (os.platform() !== 'win32') {
|
291 |
|
292 | cgiData['process.uid'] = process.getuid();
|
293 | cgiData['process.gid'] = process.getgid();
|
294 | }
|
295 |
|
296 | cgiData['process.cwd'] = process.cwd();
|
297 | cgiData['process.execPath'] = process.execPath;
|
298 | cgiData['process.version'] = process.version;
|
299 | cgiData['process.argv'] = process.argv;
|
300 | cgiData['process.memoryUsage'] = process.memoryUsage();
|
301 | cgiData['os.loadavg'] = os.loadavg();
|
302 | cgiData['os.uptime'] = os.uptime();
|
303 |
|
304 | return cgiData;
|
305 | };
|
306 |
|
307 | Airbrake.prototype.contextJSON = function(err) {
|
308 | var context = {};
|
309 | context.notifier = {
|
310 | name: 'node-airbrake',
|
311 | version: Airbrake.PACKAGE.version,
|
312 | url: Airbrake.PACKAGE.homepage
|
313 | };
|
314 |
|
315 | context.environment = this.env;
|
316 | context.rootDirectory = this.projectRoot;
|
317 | context.os = os.type();
|
318 | context.hostname = os.hostname();
|
319 | context.url = url.resolve(this.host, err.url || '');
|
320 | context.userAgent = err.ua;
|
321 | context.component = err.component;
|
322 | context.action = err.action;
|
323 | context.severity = err.severity || DEFAULT_SEVERITY;
|
324 |
|
325 | return context;
|
326 | };
|
327 |
|
328 | Airbrake.prototype.notifyJSON = function(err) {
|
329 | var trace = stackTrace.parse(err);
|
330 | var self = this;
|
331 |
|
332 | return {
|
333 | errors: [
|
334 | {
|
335 | type: err.type || 'Error',
|
336 | message: err.message,
|
337 | backtrace: trace.map(function(callSite) {
|
338 | return {
|
339 | file: callSite.getFileName() || '',
|
340 | line: callSite.getLineNumber(),
|
341 | function: callSite.getFunctionName() || ''
|
342 | };
|
343 | })
|
344 | }],
|
345 | environment: self.environmentJSON(err),
|
346 | context: self.contextJSON(err),
|
347 | session: self.sessionVars(err),
|
348 | params: self.paramsVars(err)
|
349 | };
|
350 | };
|
351 |
|
352 | Airbrake.prototype.sessionVars = function(err) {
|
353 | return (typeof err.session === 'object')
|
354 | ? err.session
|
355 | : {};
|
356 | };
|
357 |
|
358 | Airbrake.prototype.paramsVars = function(err) {
|
359 | return (typeof err.params === 'object')
|
360 | ? err.params
|
361 | : {};
|
362 | };
|
363 |
|
364 | Airbrake.prototype.trackDeployment = function(params, cb) {
|
365 | var callback = cb;
|
366 | var deploymentParams = params || {};
|
367 |
|
368 | if (typeof deploymentParams === 'function') {
|
369 | callback = deploymentParams;
|
370 | deploymentParams = {};
|
371 | }
|
372 |
|
373 | deploymentParams = merge({
|
374 | key: this.key,
|
375 | env: this.env,
|
376 | user: process.env.USER,
|
377 | rev: execSync('git rev-parse HEAD').toString().trim(),
|
378 | repo: execSync('git config --get remote.origin.url').toString().trim()
|
379 | }, deploymentParams);
|
380 |
|
381 | var body = this.deploymentPostData(deploymentParams);
|
382 |
|
383 | var options = merge({
|
384 | method: 'POST',
|
385 | url: this.url('/api/v4/projects/' + this.projectId + '/deploys?key=' + this.key),
|
386 | body: body,
|
387 | timeout: this.timeout,
|
388 | headers: {
|
389 | 'Content-Length': body.length,
|
390 | 'Content-Type': 'application/json'
|
391 | },
|
392 | proxy: this.proxy
|
393 | }, this.requestOptions);
|
394 |
|
395 | var requestCallback = this._callback(callback);
|
396 |
|
397 | request(options, function(err, res, responseBody) {
|
398 | if (err) {
|
399 | return requestCallback(err);
|
400 | }
|
401 |
|
402 | if (res.statusCode >= 300) {
|
403 | var status = HTTP_STATUS_CODES[res.statusCode];
|
404 | return requestCallback(new Error(
|
405 | 'Deployment failed: ' + res.statusCode + ' ' + status + ': ' + responseBody
|
406 | ));
|
407 | }
|
408 |
|
409 | return requestCallback(null, deploymentParams);
|
410 | });
|
411 | };
|
412 |
|
413 | Airbrake.prototype.deploymentPostData = function(params) {
|
414 | return JSON.stringify({
|
415 | version: 'v2.0',
|
416 | environment: params.env,
|
417 | username: params.user,
|
418 | revision: params.rev,
|
419 | repository: params.repo
|
420 | });
|
421 | };
|
422 |
|
423 | module.exports = Airbrake;
|