diff --git a/lib/translator/error-info-interpreter.js b/lib/translator/error-info-interpreter.js index 4339b1d..e7b852d 100644 --- a/lib/translator/error-info-interpreter.js +++ b/lib/translator/error-info-interpreter.js @@ -17,7 +17,20 @@ class ErrorInfoInterpreter { code = err; } else if (err instanceof Error) { - code = err.message; + let parseOfMessage; + + try { + parseOfMessage = JSON.parse(err.message); + } catch (e) { + parseOfMessage = err.message; + } + + if (parseOfMessage instanceof Object) { + code = parseOfMessage.code; + custom = parseOfMessage.custom; + } else { + code = parseOfMessage; + } } else if (err instanceof Object) { code = err.code; diff --git a/test/unit/lib/translator/error-info-interpreter-tests.js b/test/unit/lib/translator/error-info-interpreter-tests.js index 16dcd6e..730f4e4 100644 --- a/test/unit/lib/translator/error-info-interpreter-tests.js +++ b/test/unit/lib/translator/error-info-interpreter-tests.js @@ -58,6 +58,20 @@ describe('ErrorInfoInterpreter', function () { errorInfo.should.have.property('code', code); errorInfo.should.have.property('custom').which.is.Undefined(); }); + + it('should interpret an error thrown (string of json) as an error', function () { + let interpreter = new ErrorInfoInterpreter(errors); + + let code = 'INVALID_REQUEST'; + let custom = { data: 'anything' }; + + let errorInfo = interpreter.interpret(new Error(JSON.stringify({ code, custom }))); + + should.exist(errorInfo); + Object.keys(errorInfo).should.have.length(2); + errorInfo.should.have.property('code', code); + errorInfo.should.have.property('custom').which.is.Undefined(); + }); it('should interpret an error thrown as an object', function () { let interpreter = new ErrorInfoInterpreter(errors);