Skip to content

Commit

Permalink
feat(createError): inherit fields from cause (#795)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pooya@pi0.io>
  • Loading branch information
jerelmiller and pi0 authored Jul 7, 2024
1 parent 2009428 commit 4d67f19
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 16 deletions.
42 changes: 26 additions & 16 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,11 @@ export function createError<DataT = unknown>(
return input;
}

// Inherit H3Error properties from cause as fallback
const cause: unknown = input.cause;

const err = new H3Error<DataT>(input.message ?? input.statusMessage ?? "", {
cause: input.cause || input,
cause: cause || input,
});

if (hasProp(input, "stack")) {
Expand All @@ -117,25 +120,32 @@ export function createError<DataT = unknown>(
err.data = input.data;
}

if (input.statusCode) {
err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
} else if (input.status) {
err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
}
if (input.statusMessage) {
err.statusMessage = input.statusMessage;
} else if (input.statusText) {
err.statusMessage = input.statusText as string;
const statusCode =
input.statusCode ??
input.status ??
(cause as H3Error)?.statusCode ??
(cause as { status?: number })?.status;
if (typeof statusCode === "number") {
err.statusCode = sanitizeStatusCode(statusCode);
}
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;
Expand Down
20 changes: 20 additions & 0 deletions test/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,24 @@ describe("error", () => {

expect(ctx.errors[0].cause).toBeInstanceOf(CustomError);
});

it("can inherit from cause", async () => {
class CustomError extends Error {
cause = createError({
statusCode: 400,
statusMessage: "Bad Request",
unhandled: true,
fatal: true,
});
}

ctx.app.use("/", () => {
throw createError(new CustomError());
});

const res = await ctx.request.get("/");
expect(res.status).toBe(400);
expect(ctx.errors[0].unhandled).toBe(true);
expect(ctx.errors[0].fatal).toBe(true);
});
});

0 comments on commit 4d67f19

Please sign in to comment.