-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
125 lines (110 loc) · 2.89 KB
/
index.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
const http = require('http');
const https = require('https');
const path = require('path');
const config = {
initialized: false,
};
const formatMessage = (error) => {
const dir = process.cwd();
const json = require(path.resolve(path.join(dir, '/package.json')));
const header = [
'Lastly encountered an error.',
`\n\t\t*dir*: ${dir}`,
`\n\t\t*name*: ${json.name || null}`,
`\n\t\t*ver*: ${json.version || null}`,
];
return JSON.stringify({
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: header.join(''),
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: error.stack,
}
},
{
type: 'divider'
}
]
});
};
const handleError = (error, _req, _res, next) => {
if (!error && next) { // support express library
return next();
}
if (!config.initialized) {
return console.error('Lastly is not sending error because config was not properly initialized.');
}
try {
const message = formatMessage(error);
const {
url,
secure,
hostname,
path,
callback,
} = config;
const request = (secure ? https : http).request({
hostname,
port: secure ? 443 : 80,
path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': message.length
}
}, (response) => {
console.log(`Lastly sent an error to ${url} and recieved status code: ${response.statusCode}`);
if (callback) callback(error);
});
request.on('error', error => {
console.error(`Lastly encountered an error sending to ${url}.`);
console.error(error);
});
request.write(message);
request.end();
} catch (err) {
console.error('Lastly failed to send error.', err);
}
}
module.exports = (url, callback = null) => {
try {
let error = false;
const urlPattern = /^http(s)?:\/\/([^\/]*)(.*)/
if (typeof url !== 'string') {
console.error(`url [${url}] is not a valid string.`);
error = true;
} else {
const patternMatch = url.match(urlPattern);
if (patternMatch && patternMatch.length === 4) {
config.secure = patternMatch[1] === 's';
config.hostname = patternMatch[2];
config.path = patternMatch[3] || '/';
} else {
console.error(`url [${url}] is not a valid url.`);
error = true;
}
}
if (callback !== null && typeof callback !== 'function') {
console.error(`callback [${callback}] is not a function.`);
error = true;
}
if (!error) {
config.initialized = true;
config.url = url;
config.callback = callback;
process.on('uncaughtException', handleError);
return handleError;
}
return null;
} catch (err) {
console.error('Lastly encountered an error initializing.');
}
};