forked from goldbergyoni/nodejs-testing-best-practices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror-handling.js
54 lines (48 loc) · 1.67 KB
/
error-handling.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
const mailer = require('./libraries/mailer');
const logger = require('./libraries/logger');
// This file simulates real-world error handler that makes this component observable
const errorHandler = {
handleError: async (errorToHandle) => {
try {
logger.error(errorToHandle);
metricsExporter.fireMetric('error', {
errorName: errorToHandle.name || 'generic-error',
});
// This is used to simulate sending email to admin when an error occurs
// In real world - The right flow is sending alerts from the monitoring system
await mailer.send(
'Error occured',
`Error is ${errorToHandle}`,
'admin@our-domain.io'
);
// A common best practice is to crash when an unknown error (non-trusted) is being thrown
decideWhetherToCrash(errorToHandle);
} catch (e) {
// Continue the code flow if failed to handle the error
console.log(`handleError threw an error ${e}`);
}
},
};
const decideWhetherToCrash = (error) => {
if (!error.isTrusted) {
process.exit();
}
};
class AppError extends Error {
constructor(name, message, HTTPStatus, isTrusted) {
super(message);
this.name = name;
this.status = HTTPStatus;
this.isTrusted = isTrusted === undefined ? true : false;
}
}
// This simulates a typical monitoring solution that allow firing custom metrics when
// like Prometheus, DataDog, CloudWatch, etc
const metricsExporter = {
fireMetric: async (name, labels) => {
console.log('In real production code I will really fire metrics');
},
};
module.exports.errorHandler = errorHandler;
module.exports.metricsExporter = metricsExporter;
module.exports.AppError = AppError;