Skip to content

Commit

Permalink
Support errors with multiple properties, Fix #227
Browse files Browse the repository at this point in the history
  • Loading branch information
terehov committed Aug 7, 2023
1 parent 5c211b1 commit 7743ccb
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 25 deletions.
4 changes: 2 additions & 2 deletions examples/nodejs/index2.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Logger, BaseLogger } from "../../src/index.js";
import { NodeRuntime } from "../../src/index.js";
import { Runtime } from "../../src/index.js";

const defaultLogObject: {
name: string;
Expand All @@ -23,7 +23,7 @@ logger.fatal("test1 %s test3", "test2");

console.log("###############");

const baseLogger = new BaseLogger(NodeRuntime, {}, defaultLogObject);
const baseLogger = new BaseLogger(Runtime, {}, defaultLogObject);

baseLogger.log(0, "test", "test base logger", { haha: true, password: "123456" }, ["SECRET"]);

Expand Down
8 changes: 4 additions & 4 deletions examples/nodejs/mongodb/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/nodejs/mongodb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"type": "module",
"dependencies": {
"mongodb": "^4.4.0",
"tslog": "^4.8.2",
"tslog": "^4.8.7",
"typescript": "^5.1.6"
},
"scripts": {
Expand Down
23 changes: 7 additions & 16 deletions src/BaseLogger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,22 +287,13 @@ export class BaseLogger<LogObj> {
}

private _cloneError<T extends Error>(error: T): T {
type ErrorProperties = keyof Error;
const ErrorConstructor = error.constructor as new (...args: unknown[]) => T;
const errorProperties = Object.getOwnPropertyNames(error) as ErrorProperties[];
const errorArgs = errorProperties.map((propName) => error[propName]);

const newError = new ErrorConstructor(...errorArgs);
Object.assign(newError, error);

for (const propName of errorProperties) {
const propDesc = Object.getOwnPropertyDescriptor(newError, propName);
if (propDesc) {
propDesc.writable = true;
Object.defineProperty(newError, propName, propDesc);
}
}
return newError;
const cloned = new (error.constructor as { new (): T })();

Object.getOwnPropertyNames(error).forEach((key) => {
(cloned as any)[key] = (error as any)[key];
});

return cloned;
}

private _toErrorObject(error: Error): IErrorObject {
Expand Down
9 changes: 8 additions & 1 deletion src/runtime/browser/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,14 @@ export function prettyFormatErrorObj<LogObj>(error: Error, settings: ISettings<L

const placeholderValuesError = {
errorName: ` ${error.name} `,
errorMessage: error.message,
errorMessage: Object.getOwnPropertyNames(error)
.reduce((result: string[], key) => {
if (key !== "stack") {
result.push((error as any)[key]);
}
return result;
}, [])
.join(", "),
errorStack: errorStackStr.join("\n"),
};
return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
Expand Down
10 changes: 9 additions & 1 deletion src/runtime/nodejs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { normalize as fileNormalize } from "path";
import { types, formatWithOptions, InspectOptions } from "util";
import { Runtime, ILogObjMeta, ISettings, IStackFrame } from "../../interfaces.js";
import { formatTemplate } from "../../formatTemplate.js";
import { stdout } from "process";
export { InspectOptions };

export default {
Expand Down Expand Up @@ -132,7 +133,14 @@ export function prettyFormatErrorObj<LogObj>(error: Error, settings: ISettings<L

const placeholderValuesError = {
errorName: ` ${error.name} `,
errorMessage: error.message,
errorMessage: Object.getOwnPropertyNames(error)
.reduce((result: string[], key) => {
if (key !== "stack") {
result.push((error as any)[key]);
}
return result;
}, [])
.join(", "),
errorStack: errorStackStr.join("\n"),
};
return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
Expand Down
21 changes: 21 additions & 0 deletions tests/Nodejs/5_pretty_Log_Types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import { Logger } from "../../src";
import { getConsoleLog, mockConsoleLog } from "./helper.js";
import { stdout } from "process";

class CustomError extends Error {
constructor(message: string, public extraInfo: string) {
super(message);
Object.setPrototypeOf(this, CustomError.prototype);
}
}

describe("Pretty: Log Types", () => {
beforeEach(() => {
mockConsoleLog(true, false);
Expand Down Expand Up @@ -117,6 +124,20 @@ describe("Pretty: Log Types", () => {
expect((errorLog?.stack as any)[0]?.fileName).toBe("5_pretty_Log_Types.test.ts");
});

test("Error with multiple parameters", (): void => {
const logger = new Logger({ type: "pretty" });
const errorLog = logger.log(1234, "testLevel", new CustomError("Something went wrong", "Additional info"));
expect(getConsoleLog()).toContain("Something went wrong");
expect(getConsoleLog()).toContain("Additional info");
expect(getConsoleLog()).toContain("Error");
expect(getConsoleLog()).toContain("test");
expect(getConsoleLog()).toContain("error stack:\n");
expect(getConsoleLog()).toContain("5_pretty_Log_Types.test.ts");
expect(getConsoleLog()).toContain("Object.<anonymous>");
expect(errorLog?.nativeError).toBeInstanceOf(Error);
expect((errorLog?.stack as any)[0]?.fileName).toBe("5_pretty_Log_Types.test.ts");
});

test("string and Error", (): void => {
const logger = new Logger({ type: "pretty" });
const errorLog = logger.log(1234, "testLevel", "test", new Error("test"));
Expand Down

0 comments on commit 7743ccb

Please sign in to comment.