From 399a786986841b089cc68b5a5f06fc7b95e6b16a Mon Sep 17 00:00:00 2001 From: Perryvw Date: Sat, 23 Sep 2023 17:23:37 +0200 Subject: [PATCH] Do not cause unrelated exception when throwing Error object in environment without debug module --- src/lualib/Error.ts | 7 +++++-- test/unit/error.spec.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/lualib/Error.ts b/src/lualib/Error.ts index fa1fa0bc0..ea9cba478 100644 --- a/src/lualib/Error.ts +++ b/src/lualib/Error.ts @@ -3,7 +3,10 @@ interface ErrorType { new (...args: any[]): Error; } -function getErrorStack(constructor: () => any): string { +function getErrorStack(constructor: () => any): string | undefined { + // If debug module is not available in this environment, don't bother trying to get stack trace + if (debug === undefined) return undefined; + let level = 1; while (true) { const info = debug.getinfo(level, "f"); @@ -49,7 +52,7 @@ function initErrorClass(Type: ErrorType, name: string): any { export const Error: ErrorConstructor = initErrorClass( class implements Error { public name = "Error"; - public stack: string; + public stack?: string; constructor(public message = "") { this.stack = getErrorStack((this.constructor as any).new); diff --git a/test/unit/error.spec.ts b/test/unit/error.spec.ts index 705ee77f0..388fee290 100644 --- a/test/unit/error.spec.ts +++ b/test/unit/error.spec.ts @@ -324,3 +324,22 @@ test.each([...builtinErrors, "CustomError"])("get stack from %s", errorType => { expect(stack).toMatch("innerFunction"); expect(stack).toMatch("outerFunction"); }); + +test("still works without debug module", () => { + util.testFunction` + try + { + throw new Error("hello, world"); + } + catch (e) + { + return e; + } + ` + .setLuaHeader("debug = nil") + .expectToEqual({ + message: "hello, world", + name: "Error", + stack: undefined, + }); +});