Skip to content

Commit

Permalink
fix: issue with error serialization
Browse files Browse the repository at this point in the history
NOTE: encountered a weird case where error is not considered an instance
of Error during JSON.stringify with custom replacer.

const err = new HttpStatusError(202, 'ok')

JSON.stringify({ error: err }, customReplacers) was producing
the following results

replacer(key, value) {
  // when key === '' - top level
  value.error instanceof Error === true

  // when key === 'error'
  value instanceof Errorr === false
}

This works around it as our common shape for reply is { error, data }
  • Loading branch information
AVVS committed Nov 13, 2019
1 parent ad7606e commit 8f72f0a
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
6 changes: 5 additions & 1 deletion src/utils/serialization.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,14 @@ function deserializeError(error) {
}

function jsonSerializer(key, value) {
if (is.instance(value, Error)) {
if (value instanceof Error) {
return serializeError(value);
}

if (value && value.error instanceof Error) {
value.error = serializeError(value.error);
}

return value;
}

Expand Down
19 changes: 16 additions & 3 deletions test/amqp-transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,16 @@ describe('AMQPTransport', function AMQPTransportTestSuite() {
cache: 100,
exchange: configuration.exchange,
queue: 'test-queue',
listen: 'test.default',
listen: ['test.default', 'test.throw'],
connection: configuration.connection,
};

const amqp = await AMQPTransport.connect(opts, (message, headers, actions, callback) => {
callback(null, {
const amqp = await AMQPTransport.connect(opts, (message, properties, actions, callback) => {
if (properties.routingKey === 'test.throw') {
return callback(new HttpStatusError(202, 'ok'));
}

return callback(null, {
resp: typeof message === 'object' ? message : `${message}-response`,
time: process.hrtime(),
});
Expand All @@ -187,6 +191,15 @@ describe('AMQPTransport', function AMQPTransportTestSuite() {
))
));

it('error is correctly deserialized', async () => {
await assert.rejects(this.amqp.publishAndWait('test.throw', {}), {
name: 'HttpStatusError',
message: 'ok',
statusCode: 202,
status_code: 202,
});
});

it('is able to publish to route consumer', async () => {
const response = await this.amqp
.publishAndWait('test.default', 'test-message');
Expand Down

0 comments on commit 8f72f0a

Please sign in to comment.