Skip to content

Commit

Permalink
Wrap calls to format.transform with try / catch. (winstonjs#1347)
Browse files Browse the repository at this point in the history
* [fix] Wrap calls to `format.transform` with try / catch. Potential fix for winstonjs#1261.

* [test] Test error trapping for user-defined formats.
  • Loading branch information
indexzero authored Jun 3, 2018
1 parent 6f87466 commit ee57fa5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/winston/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,17 @@ class Logger extends stream.Transform {
}

// Here we write to the `format` pipe-chain, which on `readable` above will
// push the formatted `info` Object onto the buffer for this instance.
this.push(this.format.transform(info, this.format.options));
callback();
// push the formatted `info` Object onto the buffer for this instance. We trap
// (and re-throw) any errors generated by the user-provided format, but also
// guarantee that the streams callback is invoked so that we can continue flowing.
try {
this.push(this.format.transform(info, this.format.options));
} catch (ex) {
throw ex;
} finally {
// eslint-disable-next-line callback-return
callback();
}
}

/**
Expand Down
35 changes: 35 additions & 0 deletions test/logger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,41 @@ describe('Logger (stream semantics)', function () {

setImmediate(() => logger.end());
});

it(`rethrows errors from user-defined formats`, function () {
stdMocks.use();
const logger = winston.createLogger( {
transports: [new winston.transports.Console()],
format: winston.format.printf((info) => {
// Set a trap.
if (info.message === 'ENDOR') {
throw new Error('ITS A TRAP!');
}

return info.message;
})
});

// Trigger the trap. Swallow the error so processing continues.
try {
logger.info('ENDOR');
} catch (err) {
assume(err.message).equals('ITS A TRAP!');
}

const expected = [
'Now witness the power of the fully armed and operational logger',
'Consider the philosophical and metaphysical – BANANA BANANA BANANA',
'I was god once. I saw – you were doing well until everyone died.'
];

expected.forEach(msg => logger.info(msg));

stdMocks.restore();
const actual = stdMocks.flush();
assume(actual.stdout).deep.equals(expected.map(msg => `${msg}\n`));
assume(actual.stderr).deep.equals([]);
});
});

describe('Logger (logging exotic data types)', function () {
Expand Down

0 comments on commit ee57fa5

Please sign in to comment.