Skip to content

Commit

Permalink
Clone errors before masking and make fields writable, fix #217
Browse files Browse the repository at this point in the history
  • Loading branch information
terehov committed Feb 23, 2023
1 parent 6352c32 commit a5a0ac2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
15 changes: 15 additions & 0 deletions examples/nodejs/index2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,18 @@ const log = new Logger({
log.info(error);

////////////////////////////

function createReadonlyError(message: string, property: string) {
const error = new Error(message);
Object.defineProperty(error, "property", {
value: property,
writable: false,
enumerable: true,
configurable: false,
});
return error;
}

const e = createReadonlyError("message", "property");

logger.error(e);
17 changes: 16 additions & 1 deletion src/BaseLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ export class BaseLogger<LogObj> {
? this.settings.maskPlaceholder
: this._recursiveCloneAndMaskValuesOfKeys((source as { [key: string]: unknown })[prop], keys, seen);
return o;
}, source)
}, this._cloneError(source as Error))
: source != null && typeof source === "object"
? Object.getOwnPropertyNames(source).reduce((o, prop) => {
// mask
Expand Down Expand Up @@ -275,6 +275,21 @@ export class BaseLogger<LogObj> {
return clonedLogObj;
}

private _cloneError<T extends Error>(error: T): T {
const ErrorConstructor = error.constructor as new (message?: string) => T;
const newError = new ErrorConstructor(error.message);
Object.assign(newError, error);
const propertyNames = Object.getOwnPropertyNames(newError);
for (const propName of propertyNames) {
const propDesc = Object.getOwnPropertyDescriptor(newError, propName);
if (propDesc) {
propDesc.writable = true;
Object.defineProperty(newError, propName, propDesc);
}
}
return newError;
}

private _toErrorObject(error: Error): IErrorObject {
return {
nativeError: error,
Expand Down

0 comments on commit a5a0ac2

Please sign in to comment.