Add Errors.toLogFormat

Allows errors to be formatted and sanitized for logging. Removes sensitive paths
such as the app root directory.

Ideally, this module would be called singular `Error` but that is already a
global name. Using `Errors` plural is  similar to Java convention for utilities
such as `Arrays`, `Collections`, `Files`, etc. See:
https://stackoverflow.com/a/11673838
This commit is contained in:
Daniel Gasienica 2018-03-06 12:04:37 -05:00
parent 77e7e9ad4d
commit be3e4d86c2
2 changed files with 56 additions and 0 deletions

View file

@ -0,0 +1,17 @@
/* eslint-env node */
const Path = require('path');
const toError = require('ensure-error');
const APP_ROOT_PATH = Path.join(__dirname, '..', '..', '..');
const APP_ROOT_PATH_PATTERN = new RegExp(APP_ROOT_PATH, 'g');
// toLogFormat :: Error -> String
exports.toLogFormat = (error) => {
const normalizedError = toError(error);
const stackWithoutPrivatePaths =
normalizedError.stack.replace(APP_ROOT_PATH_PATTERN, '<REDACTED_PATH>');
return stackWithoutPrivatePaths;
};

View file

@ -0,0 +1,39 @@
const Path = require('path');
const { assert } = require('chai');
const Errors = require('../../../js/modules/types/errors');
const APP_ROOT_PATH = Path.join(__dirname, '..', '..', '..');
describe('Errors', () => {
describe('toLogFormat', () => {
it('should redact sensitive paths in stack trace', () => {
try {
throw new Error('boom');
} catch (error) {
assert.include(
error.stack,
APP_ROOT_PATH,
'Unformatted stack has sensitive paths'
);
const formattedStack = Errors.toLogFormat(error);
assert.notInclude(
formattedStack,
APP_ROOT_PATH,
'Formatted stack does not have sensitive paths'
);
assert.include(
formattedStack,
'<REDACTED_PATH>',
'Formatted stack has redactions'
);
return;
}
// eslint-disable-next-line no-unreachable
assert.fail('Expected error to be thrown.');
});
});
});