Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/hooks.server.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { RequestEvent } from "@sveltejs/kit";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";

const { captureException } = vi.hoisted(() => ({ captureException: vi.fn() }));

vi.mock("#lib/server/posthog", () => ({
posthog: { captureException },
}));

const { handleError } = await import("./hooks.server");

const event = {
locals: {
posthogError: { distinctId: "user-1", properties: { $session_id: "session-1" } },
},
} as unknown as RequestEvent;

describe("handleError", () => {
beforeEach(() => {
captureException.mockReset();
});

it("does not report a framework 404", () => {
handleError({ kind: "framework", error: { status: 404, message: "Not Found" }, event });
expect(captureException).not.toHaveBeenCalled();
});

it("does not report an app 404", () => {
handleError({ kind: "app", error: { status: 404, message: "Not Found" }, event });
expect(captureException).not.toHaveBeenCalled();
});

it("reports a framework error that is not a 404", () => {
const error = { status: 405, message: "Method Not Allowed" };
handleError({ kind: "framework", error, event });
expect(captureException).toHaveBeenCalledWith(error, {
distinctId: "user-1",
properties: { $session_id: "session-1" },
});
});

it("reports an unknown error", () => {
const error = new Error("boom");
expect(handleError({ kind: "unknown", error, event })).toEqual({ message: "boom" });
expect(captureException).toHaveBeenCalledWith(error, {
distinctId: "user-1",
properties: { $session_id: "session-1" },
});
});
});
13 changes: 8 additions & 5 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,13 @@ export async function handle({ event, resolve }) {
);
}

export function handleError({ error, event }) {
posthog.captureException(error, {
distinctId: event.locals.posthogError?.distinctId,
properties: event.locals.posthogError?.properties,
});
export function handleError({ error, event, kind }) {
const notFound = kind !== "unknown" && error.status === 404;
if (!notFound) {
posthog.captureException(error, {
distinctId: event.locals.posthogError?.distinctId,
properties: event.locals.posthogError?.properties,
});
}
return { message: error instanceof Error ? error.message : "Internal Error" };
}
Loading