forked from expressjs/api-error-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
44 lines (33 loc) · 980 Bytes
/
index.js
File metadata and controls
44 lines (33 loc) · 980 Bytes
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
var statuses = require('statuses');
var production = process.env.NODE_ENV === 'production';
var defaultLog = function (err) {
console.error(err.stack);
};
module.exports = function (options) {
var opts = options || {};
var log = opts.log || defaultLog;
return function apiErrorHandler(err, req, res, next) {
var status = err.status || err.statusCode || 500;
if (status < 400) status = 500;
res.statusCode = status;
var body = {
status: status
};
// show the stacktrace when not in production
// TODO: make this an option
if (!production) body.stack = err.stack;
// internal server errors
if (status >= 500) {
log(err, req, res);
body.message = statuses[status];
res.json(body);
return;
}
// client errors
body.message = err.message;
if (err.code) body.code = err.code;
if (err.name) body.name = err.name;
if (err.type) body.type = err.type;
res.json(body);
}
}