diff --git a/src/index.js b/src/index.js index 8de1e6c..10447af 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ import { flattenDeep, get, first, + forEach, isArray, isEmpty, includes, @@ -579,6 +580,19 @@ 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; @@ -586,8 +600,8 @@ export const mapErrorToObject = (error, options = {}) => { 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); diff --git a/test/index.spec.js b/test/index.spec.js index b3066b1..51cae97 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -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', + }, + }, }); }); });