Skip to content

Commit

Permalink
refactor: improve error to object use cases
Browse files Browse the repository at this point in the history
  • Loading branch information
lykmapipo committed Apr 1, 2019
1 parent f296400 commit 1a4fed7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 7 deletions.
18 changes: 16 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
flattenDeep,
get,
first,
forEach,
isArray,
isEmpty,
includes,
Expand Down Expand Up @@ -579,15 +580,28 @@ export const mapErrorToObject = (error, options = {}) => {
description,
} = mergeObjects(options);

// normalize errors bag
const bagify = (errors = {}) => {
const bag = {};
// simplify error bag
forEach(errors, (value = {}, key) => {
const simple = pick(value, 'message', 'name', 'kind', 'path', 'value');
const type = get(value, 'properties.type');
bag[key] = mergeObjects(simple, { type });
});
// return errors bag
return bag;
};

// prepare error payload
const body = {};
body.code = error.code || code;
body.status = error.status || status || code;
body.name = error.name || name;
body.message = error.message || message || STATUS_CODES[code];
body.description = error.description || description || body.message;
body.errors = error.errors || undefined; // error bag
body.stack = stack ? error.stack : undefined; // error stack
body.errors = error.errors ? bagify(error.errors) : undefined;
body.stack = stack ? error.stack : undefined;

// return formatted error response
return mergeObjects(body);
Expand Down
38 changes: 33 additions & 5 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -262,15 +262,43 @@ describe('common', () => {
expect(object.stack).to.exist;
});

it('should normalize errors in error instance', () => {
const error = new Error();
const object = mapErrorToObject(error);
it('should normalize errors bag in error instance', () => {
const errors = {
name: {
message: 'Path `name` (John Doe) is not unique.',
name: 'ValidatorError',
properties: {
type: 'unique',
path: 'name',
value: 'John Doe',
message: 'Path `name` (John Doe) is not unique.',
reason: 'E11000 duplicate key error collection',
},
kind: 'unique',
path: 'name',
value: 'John Doe',
reason: 'E11000 duplicate key error collection',
},
};
const error = new Error('Validation Error');
error.errors = errors;
const object = mapErrorToObject(error, { name: 'ValidationError' });
expect(object).to.be.eql({
status: 500,
code: 500,
name: 'Error',
message: 'Internal Server Error',
description: 'Internal Server Error',
message: 'Validation Error',
description: 'Validation Error',
errors: {
name: {
message: 'Path `name` (John Doe) is not unique.',
name: 'ValidatorError',
type: 'unique',
kind: 'unique',
path: 'name',
value: 'John Doe',
},
},
});
});
});

0 comments on commit 1a4fed7

Please sign in to comment.