-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (41 loc) · 1.24 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
const {
parseStackTrace,
printStackTrace
} = require('superror');
const highlight = require('./highlight');
const { readFile } = require('fs').promises;
const call = p =>
p.then(r => [null, r], e => [e]);
const { NODE_ENV = 'development' } = process.env;
const handleError = async (err, res) => {
const year = new Date().getFullYear();
if (err instanceof Error) {
const [stack] = parseStackTrace(err.stack);
const { location, line, column } = stack;
console.error(err.name, err.message, `at ${location}:${line}:${column}`);
const [ferr, code] = await call(readFile(location, 'utf8'));
if (!ferr) {
const output = printStackTrace(code, line, column);
console.error(highlight(output));
}
}
if (res.statusCode / 100 | 0 != 5) {
res.statusCode = 500;
}
res.writeHead(res.statusCode, {
'Content-Type': 'text/html'
});
res.write('<h2>Server Internal Error</h2>');
if (NODE_ENV === 'development')
res.write(`<pre>${err.stack}</pre>`);
res.write('<hr />');
res.write(`Powered by <a href="https://github.com/kelpjs/kelp-error" >kelp-error</a> © ` + year);
res.end();
};
module.exports = async (req, res, next) => {
try {
await next();
} catch (err) {
handleError(err, res);
}
}