improves error structure
This commit is contained in:
18
src/errors/formatResponse.js
Normal file
18
src/errors/formatResponse.js
Normal file
@@ -0,0 +1,18 @@
|
||||
const formatErrorResponse = (incoming, source) => {
|
||||
switch (source) {
|
||||
case 'mongoose':
|
||||
return {
|
||||
errors: Object.keys(incoming.errors).reduce((acc, key) => {
|
||||
acc.push({
|
||||
message: incoming.errors[key].message,
|
||||
});
|
||||
return acc;
|
||||
}, []),
|
||||
};
|
||||
|
||||
default:
|
||||
return incoming;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = formatErrorResponse;
|
||||
@@ -1,14 +0,0 @@
|
||||
const errorFormatter = (incoming, source) => {
|
||||
switch (source) {
|
||||
case 'mongoose':
|
||||
return Object.keys(incoming.errors).reduce((acc, key) => {
|
||||
acc.push(incoming.errors[key].message);
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
default:
|
||||
return incoming;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = errorFormatter;
|
||||
@@ -1,11 +1,11 @@
|
||||
const httpStatus = require('http-status');
|
||||
const errorFormatter = require('../../errors/formatter');
|
||||
const formatErrorResponse = require('../../errors/formatResponse');
|
||||
|
||||
const create = (req, res) => {
|
||||
req.model.create(req.body, (err, result) => {
|
||||
if (err) {
|
||||
res.status(httpStatus.INTERNAL_SERVER_ERROR)
|
||||
.json(errorFormatter(err, 'mongoose'));
|
||||
.json(formatErrorResponse(err, 'mongoose'));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user