diff --git a/src/error.ts b/src/error.ts index ed669b38..784c25a8 100644 --- a/src/error.ts +++ b/src/error.ts @@ -93,8 +93,11 @@ export function createError( return input; } + // Inherit H3Error properties from cause as fallback + const cause: unknown = input.cause; + const err = new H3Error(input.message ?? input.statusMessage ?? "", { - cause: input.cause || input, + cause: cause || input, }); if (hasProp(input, "stack")) { @@ -120,27 +123,29 @@ export function createError( const statusCode = input.statusCode ?? input.status ?? - (input?.cause as H3Error)?.statusCode ?? - (input?.cause as { status?: number })?.status; - + (cause as H3Error)?.statusCode ?? + (cause as { status?: number })?.status; if (typeof statusCode === "number") { - err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode); + err.statusCode = sanitizeStatusCode(statusCode); } - if (input.statusMessage) { - err.statusMessage = input.statusMessage; - } else if (input.statusText) { - err.statusMessage = input.statusText as string; - } - if (err.statusMessage) { - err.statusMessage = sanitizeStatusMessage(err.statusMessage); + const statusMessage = + input.statusMessage ?? + input.statusText ?? + (cause as H3Error)?.statusMessage ?? + (cause as { statusText?: string })?.statusText; + if (statusMessage) { + err.statusMessage = sanitizeStatusMessage(statusMessage); } - if (input.fatal !== undefined) { - err.fatal = input.fatal; + const fatal = input.fatal ?? (cause as H3Error)?.fatal; + if (fatal !== undefined) { + err.fatal = fatal; } - if (input.unhandled !== undefined) { - err.unhandled = input.unhandled; + + const unhandled = input.unhandled ?? (cause as H3Error)?.unhandled; + if (unhandled !== undefined) { + err.unhandled = unhandled; } return err; diff --git a/test/error.test.ts b/test/error.test.ts index b1dfd3ee..c92146cd 100644 --- a/test/error.test.ts +++ b/test/error.test.ts @@ -113,12 +113,9 @@ describe("error", () => { cause = new HttpError(); } - ctx.app.use( - "/", - eventHandler(() => { - throw createError(new CustomError()); - }), - ); + ctx.app.use("/", () => { + throw createError(new CustomError()); + }); const res = await ctx.request.get("/"); expect(res.status).toBe(400);