forked from GlennGeenen/boomhandler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
71 lines (60 loc) · 1.56 KB
/
Copy pathindex.js
File metadata and controls
71 lines (60 loc) · 1.56 KB
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
'use strict';
const inspect = require('util').inspect;
function stringify(val) {
const stack = val.stack;
if (stack) {
return String(stack);
}
const str = String(val);
return str === toString.call(val)
? inspect(val)
: str;
}
function logError(err, logMethod) {
const errorString = stringify(err);
if (typeof logMethod === 'function') {
logMethod(errorString);
} else {
console.error(errorString);
}
}
function middleware(options) {
const shouldLog = options.log === undefined ? true : options.log;
return function errorHandler(err, req, res) {
if (shouldLog) {
logError(err, options.logMethod);
}
// Handle Boom Errors
if (err.isBoom) {
return res.status(err.output.statusCode).json(err.output.payload);
}
// Handle statusCode
if (err.statusCode) {
return res.status(err.statusCode).json({
message: err.message,
error: err.name,
statusCode: err.statusCode,
});
}
// Handle Mongoose Errors
if (err.name === 'CastError') {
return res.status(400).json({
message: 'A cast error occured.',
error: 'Bad Request',
statusCode: 400,
});
} else if (err.name === 'ValidationError') {
return res.status(400).json({
message: 'A validation error occured.',
error: 'Bad Request',
statusCode: 400,
});
}
return res.status(500).json({
message: 'An internal server error occurred',
error: 'Internal Server Error',
statusCode: 500,
});
};
}
module.exports = middleware;