forked from rollbar/node_rollbar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollbar.js
320 lines (287 loc) · 9.83 KB
/
rollbar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*jslint devel: true, nomen: true, indent: 2, maxlen: 100 */
"use strict";
var logger = require('./lib/logger');
var api = require('./lib/api');
var notifier = require('./lib/notifier');
var parser = require('./lib/parser');
var RollbarError = require('./lib/error');
var initialized = false;
/**
*
* Rollbar:
*
* Handle caught and uncaught exceptions, and report messages back to rollbar.
*
* This library requires an account at http://rollbar.com/.
*
* Example usage:
*
* Express -
*
* var express = require('express');
* var rollbar = require('rollbar');
*
* var app = express();
*
* app.get('/', function (req, res) {
* ...
* });
*
* // Use the rollbar error handler to send exceptions to your rollbar account
* app.use(rollbar.errorHandler('ROLLBAR_ACCESS_TOKEN'));
*
* app.listen(6943);
*
* Standalone -
*
* var rollbar = require('rollbar');
* rollbar.init('ROLLBAR_ACCESS_TOKEN');
* rollbar.reportMessage('Hello world', 'debug');
*
* Uncaught exceptions -
*
* var rollbar = require('rollbar');
* rollbar.handleUncaughtExceptions('ROLLBAR_ACCESS_TOKEN');
*
* Send exceptions and request data -
*
* app.get('/', function (req, res) {
* try {
* ...
* } catch (e) {
* rollbar.handleError(e, req);
* }
* });
*
* Track people -
*
* app.get('/', function (req, res) {
* req.userId = 12345; // or req.user_id
* rollbar.reportMessage('Interesting event', req);
* });
*/
exports.init = function (accessToken, options) {
/*
* Initialize the rollbar library.
*
* For more information on each option, see http://rollbar.com/docs/api_items/
*
* Supported options, (all optional):
*
* host - Default: os.hostname() - the hostname of the server the node.js process is running on
* environment - Default: 'unspecified' - the environment the code is running in. e.g. 'staging'
* endpoint - Default: 'https://api.rollbar.com/api/1/' - the url to send items to
* root - the path to your code, (not including any trailing slash) which will be used to link
* source files on rollbar
* branch - the branch in your version control system for this code
* codeVersion - the version or revision of your code
* enabled - Default: true - determines if errors gets reported to Rollbar
*
*/
if (!initialized) {
options = options || {};
if (!accessToken && options.enabled !== false) {
logger.error('Missing access_token.');
return;
}
options.environment = options.environment || process.env.NODE_ENV || 'unspecified';
api.init(accessToken, options);
notifier.init(api, options);
initialized = true;
}
};
/*
* reportMessage(message, level, request, callback)
*
* Sends a message to rollbar with optional level, request and callback.
* The callback should take a single parameter to indicate if there was an
* error.
*
* Parameters:
* message - a string to send to rollbar
* level - Default: 'error' - optional level, 'debug', 'info', 'warning', 'error', 'critical'
* request - optional request object to send along with the message
* callback - optional callback that will be invoked once the message was reported.
* callback should take 3 parameters: callback(err, payloadData, response)
*
* Examples:
*
* rollbar.reportMessage("User purchased something awesome!", "info");
*
* rollbar.reportMessage("Something suspicious...", "debug", null, function (err, payloadData) {
* if (err) {
* console.error('Error sending to Rollbar:', err);
* } else {
* console.log('Reported message to rollbar:');
* console.log(payloadData);
* }
* });
*
*/
exports.reportMessage = notifier.reportMessage;
/*
* reportMessageWithPayloadData(message, payloadData, request, callback)
*
* The same as reportMessage() but allows you to specify extra data along with the message.
*
* Parameters:
* message - a string to send to rollbar
* payloadData - an object containing key/values to be sent along with the message.
* e.g. {level: "warning", fingerprint: "CustomerFingerPrint"}
* request - optional request object to send along with the message
* callback - optional callback that will be invoked once the message has been sent to Rollbar.
* callback should take 3 parameters: callback(err, payloadData, response)
*
* Examples:
*
* rollbar.reportMessageWithPayloadData("Memcache miss",
* {level: "debug", fingerprint: "Memcache-miss"}, null, function (err) {
* // message was queued/sent to rollbar
* });
*
*/
exports.reportMessageWithPayloadData = notifier.reportMessageWithPayloadData;
/*
* handleError(err, request, callback)
*
* Send a details about the error to rollbar along with optional request information.
*
* Parameters:
* err - an Exception/Error instance
* request - an optional request object to send along with the error
* callback - optional callback that will be invoked after the error was sent to Rollbar.
* callback should take 3 parameters: callback(err, payloadData, response)
*
* Examples:
*
* rollbar.handleError(new Error("Could not connect to the database"));
*
* rollbar.handleError(new Error("it's just foobar..."), function (err) {
* // error was queued/sent to rollbar
* });
*
* rollbar.handleError(new Error("invalid request!"), req);
*
*/
exports.handleError = notifier.handleError;
/*
* handleErrorWithPayloadData(err, payloadData, request, callback)
*
* The same as handleError() but allows you to specify additional data to log along with the error,
* as well as other payload options.
*
* Parameters:
* err - an Exception/Error instance
* payloadData - an object containing keys/values to be sent along with the error report.
* e.g. {level: "warning"}
* request - optional request object to send along with the message
* callback - optional callback that will be invoked after the error was sent to Rollbar.
* callback should take 3 parameters: callback(err, payloadData, response)
*
* Examples:
*
* rollbar.handleError(new Error("Could not connect to database"), {level: "warning"});
* rollbar.handleError(new Error("Could not connect to database"),
* {custom: {someKey: "its value, otherKey: ["other", "value"]}});
* rollbar.handleError(new Error("error message"), {}, req, function (err) {
* // error was queued/sent to rollbar
* });
*/
exports.handleErrorWithPayloadData = notifier.handleErrorWithPayloadData;
exports.errorHandler = function (accessToken, options) {
/*
* A middleware handler for connect and express.js apps. For a list
* of supported options, see the init() docs above.
*
* All exceptions thrown from inside an express or connect get/post/etc... handler
* will be sent to rollbar when this middleware is installed.
*/
exports.init(accessToken, options);
return function (err, req, res, next) {
var cb = function (rollbarErr) {
if (rollbarErr) {
logger.error('Error reporting to rollbar, ignoring: ' + rollbarErr);
}
return next(err, req, res);
};
if (!err) {
return next(err, req, res);
}
if (err instanceof Error) {
return notifier.handleError(err, req, cb);
}
return notifier.reportMessage('Error: ' + err, 'error', req, cb);
};
};
exports.handleUncaughtExceptionsAndRejections = function (accessToken, options) {
exports.handleUncaughtExceptions(accessToken, options);
exports.handleUnhandledRejections(accessToken, options);
};
exports.handleUncaughtExceptions = function (accessToken, options) {
/*
* Registers a handler for the process.uncaughtException event
*
* If options.exitOnUncaughtException is set to true, the notifier will
* immediately send the uncaught exception + all queued items to rollbar,
* then call process.exit(1).
*
* Note: The node.js authors advise against using these type of handlers.
* More info: http://nodejs.org/api/process.html#process_event_uncaughtexception
*
*/
// Default to not exiting on uncaught exceptions unless options.exitOnUncaughtException is set.
options = options || {};
var exitOnUncaught = options.exitOnUncaughtException === undefined ?
false : !!options.exitOnUncaughtException;
delete options.exitOnUncaughtException;
exports.init(accessToken, options);
if (initialized) {
process.on('uncaughtException', function (err) {
logger.error('Handling uncaught exception.');
logger.error(err);
notifier.handleError(err, function (err) {
if (err) {
logger.error('Encountered an error while handling an uncaught exception.');
logger.error(err);
}
if (exitOnUncaught) {
process.exit(1);
}
});
});
} else {
logger.error('Rollbar is not initialized. Uncaught exceptions will not be tracked.');
}
};
exports.handleUnhandledRejections = function (accessToken, options) {
/*
* Registers a handler for the process.unhandledRejection event.
*/
options = options || {};
var exitOnUnhandled = options.exitOnUnhandledRejection === undefined ?
false : !!options.exitOnUnhandledRejection;
delete options.exitOnUnhandledRejection;
exports.init(accessToken, options);
if (initialized) {
process.on('unhandledRejection', function (reason) {
logger.error('Handling unhandled rejection.');
logger.error(reason);
notifier.handleError(reason, function (err) {
if (err) {
logger.error('Encountered an error while handling an unhandled rejection.');
logger.error(err);
}
if (exitOnUnhandled) {
process.exit(1);
}
})
});
} else {
logger.error('Rollbar is not initialized. Uncaught rejections will not be tracked.');
}
};
exports.wait = notifier.wait;
exports.api = api;
exports.notifier = notifier;
exports.parser = parser;
exports.Error = RollbarError;