forked from schibsted/middy-error-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (43 loc) · 1.64 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
const filterObject = (obj, predicate) =>
Object.fromEntries(Object.entries(obj).filter(([key, val]) => predicate(val, key)));
module.exports = ({ logger = console, level = 'error', exposeStackTrace = false, filter = () => true } = {}) => ({
onError: async (handler) => {
const { error } = handler;
// if there are a `statusCode` and an `error` field
// this is a valid http error object
if (filter(error) && typeof logger[level] === 'function') {
logger[level](
{
error: (({ name, message, stack, details, cause, status, statusCode, expose }) => ({
name,
message,
stack,
details,
cause,
status,
statusCode,
expose,
}))(error),
},
`${error.name ?? ''}: ${error.message ?? ''}`
);
}
// eslint-disable-next-line no-param-reassign
handler.response = {
...(handler.response ?? {}),
statusCode: error.statusCode ?? 500,
body: JSON.stringify(
filterObject(
{
statusCode: error.statusCode,
message: error.message,
details: error.details,
cause: error.cause,
stack: exposeStackTrace && filter(error) && error.stack,
},
Boolean
)
),
};
},
});