-
Notifications
You must be signed in to change notification settings - Fork 33
/
error.js
77 lines (54 loc) · 2.03 KB
/
error.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
'use strict';
const Boom = require('@hapi/boom');
const Toys = require('@hapipal/toys');
const Avocat = require('@hapipal/avocat');
const { NotFoundError, ValidationError } = require('objection');
const internals = {};
module.exports = Toys.onPreResponse((request, h) => {
const { response: error } = request;
const { formatError, mapError } = internals;
if (!error.isBoom) {
return h.continue;
}
throw formatError(mapError(error));
});
internals.mapError = (error) => {
// Handle joi input validation error.
// Info available due to default failAction in routes/helpers.
if (error.output.payload.validation) {
// e.g. '"body" is required' -> 'is required'
const stripFieldName = (str) => str.replace(/^".*?" /, '');
const { source } = error.output.payload.validation;
const validation = error.details.reduce((collector, { path, message }) => {
const field = path[path.length - 1] || source;
return {
...collector,
[field]: (collector[field] || []).concat(stripFieldName(message))
};
}, {});
return Boom.badData(null, { validation });
}
// Handle some specific db errors
if (error instanceof ValidationError) {
return Boom.badData(null, { validation: {} }); // No specifics, avoid leaking model details
}
if (error instanceof NotFoundError) {
return Boom.notFound(`${error.modelName || 'Record'} Not Found`);
}
// Handle all other db errors with avocat
return Avocat.rethrow(error, { return: true, includeMessage: false }) || error;
};
internals.formatError = (error) => {
const { message } = error.output.payload;
const payload = error.output.payload = { errors: {} };
if (error.data && error.data.validation) {
payload.errors = error.data.validation;
}
else {
const type = (error.typeof && error.typeof.name) || 'error';
payload.errors = {
[type]: [message]
};
}
return error;
};