generated from nhcarrigan/template
feat: error handling, logging, analytics, OG tags, and sticky sidebar (#44)
## Summary
- Add comprehensive try/catch error handling across all API routes, middleware, and the Hono global error handler, piping every unhandled error to the `@nhcarrigan/logger` service to prevent silent crashes and unhandled Promise rejections
- Add a `logError` utility on the frontend that forwards errors through the overridden `console.error` to the backend telemetry endpoint; apply it to every silent `catch {}` block in the game context, sound, notification, and clipboard utilities, and wrap the React tree in an `ErrorBoundary`
- Add Plausible analytics, Open Graph + Twitter Card meta tags, Tree-Nation widget, and Google Ads to `index.html`
- Make the game sidebar sticky with a `--resource-bar-height` CSS custom property offset so it stays viewport-height without overlapping the resource bar; reset sticky behaviour in the mobile responsive override
## Test plan
- [ ] Lint passes: `pnpm lint`
- [ ] Build passes: `pnpm build`
- [ ] Verify errors thrown in API routes appear in the logger service rather than crashing the process
- [ ] Verify frontend errors appear in the `/api/fe/error` backend log
- [ ] Verify Open Graph tags render correctly when sharing the URL
- [ ] Verify Plausible analytics fires on page load
- [ ] Verify Tree-Nation badge renders in the sidebar
- [ ] Verify sidebar stays fixed while the main content scrolls on desktop
- [ ] Verify mobile layout is unaffected
✨ This issue was created with help from Hikari~ 🌸
Reviewed-on: #44
Co-authored-by: Hikari <hikari@nhcarrigan.com>
Co-committed-by: Hikari <hikari@nhcarrigan.com>
This commit was merged in pull request #44.
This commit is contained in:
@@ -80,6 +80,18 @@ describe("apotheosis route", () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns apotheosis count on success", async () => {
|
||||
// Need all 15 transcendence upgrades purchased for eligibility
|
||||
const allUpgradeIds = [
|
||||
|
||||
@@ -113,5 +113,14 @@ describe("auth route", () => {
|
||||
const location = res.headers.get("Location") ?? "";
|
||||
expect(location).toContain("error=auth_failed");
|
||||
});
|
||||
|
||||
it("redirects with error when callback throws a non-Error value", async () => {
|
||||
const { app, exchangeCode } = await makeApp();
|
||||
exchangeCode.mockRejectedValueOnce("raw string error");
|
||||
const res = await app.fetch(new Request("http://localhost/auth/callback?code=bad_code"));
|
||||
expect(res.status).toBe(302);
|
||||
const location = res.headers.get("Location") ?? "";
|
||||
expect(location).toContain("error=auth_failed");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -293,4 +293,16 @@ describe("boss route", () => {
|
||||
const body = await res.json() as { won: boolean };
|
||||
expect(body.won).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await challenge({ bossId: "test_boss" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await challenge({ bossId: "test_boss" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -143,4 +143,16 @@ describe("craft route", () => {
|
||||
expect(body.recipeId).toBe(TEST_RECIPE_ID);
|
||||
expect(body.bonusType).toBe("gold_income");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post({ recipeId: TEST_RECIPE_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post({ recipeId: TEST_RECIPE_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -406,5 +406,31 @@ describe("explore route", () => {
|
||||
expect(body.materialsFound.some((m) => m.materialId === "verdant_sap")).toBe(true);
|
||||
mockRandom.mockRestore();
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws on collect", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await postCollect({ areaId: TEST_AREA_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value on collect", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await postCollect({ areaId: TEST_AREA_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /start error path", () => {
|
||||
it("returns 500 when the database throws on start", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await postStart({ areaId: TEST_AREA_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value on start", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await postStart({ areaId: TEST_AREA_ID });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/* eslint-disable max-lines-per-function -- Test suites naturally have many cases */
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { Hono } from "hono";
|
||||
|
||||
vi.mock("../../src/services/logger.js", () => ({
|
||||
logger: {
|
||||
log: vi.fn().mockResolvedValue(undefined),
|
||||
error: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("frontend route", () => {
|
||||
let loggerMock: { log: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
const { logger } = await import("../../src/services/logger.js");
|
||||
loggerMock = logger as typeof loggerMock;
|
||||
});
|
||||
|
||||
const makeApp = async () => {
|
||||
const { frontendRouter } = await import("../../src/routes/frontend.js");
|
||||
const app = new Hono();
|
||||
app.route("/frontend", frontendRouter);
|
||||
return app;
|
||||
};
|
||||
|
||||
const postLog = async (body: unknown, contentType = "application/json") => {
|
||||
const app = await makeApp();
|
||||
return app.fetch(new Request("http://localhost/frontend/log", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": contentType },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
}));
|
||||
};
|
||||
|
||||
const postError = async (body: unknown, contentType = "application/json") => {
|
||||
const app = await makeApp();
|
||||
return app.fetch(new Request("http://localhost/frontend/error", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": contentType },
|
||||
body: typeof body === "string" ? body : JSON.stringify(body),
|
||||
}));
|
||||
};
|
||||
|
||||
describe("POST /log", () => {
|
||||
it("returns 200 when level is debug and message is present", async () => {
|
||||
const res = await postLog({ level: "debug", message: "test debug" });
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json() as { ok: boolean };
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 200 when level is info and message is present", async () => {
|
||||
const res = await postLog({ level: "info", message: "test info" });
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json() as { ok: boolean };
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 200 when level is warn and message is present", async () => {
|
||||
const res = await postLog({ level: "warn", message: "test warn" });
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json() as { ok: boolean };
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 400 when level is invalid", async () => {
|
||||
const res = await postLog({ level: "error", message: "test" });
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("level and message are required");
|
||||
});
|
||||
|
||||
it("returns 400 when level is missing", async () => {
|
||||
const res = await postLog({ message: "test" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 when message is missing", async () => {
|
||||
const res = await postLog({ level: "info" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 500 when request body is invalid JSON", async () => {
|
||||
const res = await postLog("not valid json at all", "application/json");
|
||||
expect(res.status).toBe(500);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("Internal server error");
|
||||
});
|
||||
|
||||
it("returns 500 and covers non-Error branch when logger throws a raw value", async () => {
|
||||
loggerMock.log.mockImplementationOnce(() => { throw "raw string error"; });
|
||||
const res = await postLog({ level: "info", message: "test" });
|
||||
expect(res.status).toBe(500);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("Internal server error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /error", () => {
|
||||
it("returns 200 with valid context and message", async () => {
|
||||
const res = await postError({ context: "SomeComponent", message: "Something went wrong" });
|
||||
expect(res.status).toBe(200);
|
||||
const body = await res.json() as { ok: boolean };
|
||||
expect(body.ok).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 400 when context field is missing", async () => {
|
||||
const res = await postError({ message: "Something went wrong" });
|
||||
expect(res.status).toBe(400);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("context and message are required");
|
||||
});
|
||||
|
||||
it("returns 400 when message field is missing", async () => {
|
||||
const res = await postError({ context: "SomeComponent" });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 500 when request body is invalid JSON", async () => {
|
||||
const res = await postError("not valid json at all", "application/json");
|
||||
expect(res.status).toBe(500);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("Internal server error");
|
||||
});
|
||||
|
||||
it("returns 500 and covers non-Error branch when logger throws a raw value", async () => {
|
||||
loggerMock.error.mockImplementationOnce(() => { throw "raw string error"; });
|
||||
const res = await postError({ context: "SomeComponent", message: "Something went wrong" });
|
||||
expect(res.status).toBe(500);
|
||||
const body = await res.json() as { error: string };
|
||||
expect(body.error).toBe("Internal server error");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -420,6 +420,45 @@ describe("game route", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /load error path", () => {
|
||||
it("returns 500 when the database throws during load", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await app.fetch(new Request("http://localhost/game/load"));
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during load", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await app.fetch(new Request("http://localhost/game/load"));
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /save error path", () => {
|
||||
const save = (body: Record<string, unknown>) =>
|
||||
app.fetch(new Request("http://localhost/game/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}));
|
||||
|
||||
it("returns 500 when the database throws during save", async () => {
|
||||
const state = makeState();
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await save({ state });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during save", async () => {
|
||||
const state = makeState();
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await save({ state });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /reset", () => {
|
||||
const reset = () =>
|
||||
app.fetch(new Request("http://localhost/game/reset", { method: "POST" }));
|
||||
@@ -450,5 +489,17 @@ describe("game route", () => {
|
||||
const body = await res.json() as { signature: string | undefined };
|
||||
expect(typeof body.signature).toBe("string");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during reset", async () => {
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await reset();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during reset", async () => {
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await reset();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -152,6 +152,18 @@ describe("leaderboards route", () => {
|
||||
expect(typeof body.entries[0]?.activeTitle).toBe("string");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws", async () => {
|
||||
vi.mocked(prisma.player.findMany).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await get();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value", async () => {
|
||||
vi.mocked(prisma.player.findMany).mockRejectedValueOnce("raw string error");
|
||||
const res = await get();
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("defaults to 0 for game-state categories when state is missing", async () => {
|
||||
vi.mocked(prisma.player.findMany).mockResolvedValueOnce([makePlayer({ discordId: "p1" })] as never);
|
||||
vi.mocked(prisma.gameState.findMany).mockResolvedValueOnce([] as never);
|
||||
|
||||
@@ -93,6 +93,18 @@ describe("prestige route", () => {
|
||||
expect(body.runestones).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during prestige", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post("");
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during prestige", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post("");
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("updates daily challenge progress when dailyChallenges are set", async () => {
|
||||
const state = makeState({
|
||||
dailyChallenges: {
|
||||
@@ -152,5 +164,17 @@ describe("prestige route", () => {
|
||||
expect(body.runestonesRemaining).toBe(90); // 100 - 10
|
||||
expect(body.purchasedUpgradeIds).toContain("income_1");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during buy-upgrade", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post("/buy-upgrade", { upgradeId: "income_1" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during buy-upgrade", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post("/buy-upgrade", { upgradeId: "income_1" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,6 +182,18 @@ describe("profile route", () => {
|
||||
expect(unknown?.name).toBe("unknown_title_id");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during profile get", async () => {
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await app.fetch(new Request(`http://localhost/profile/${DISCORD_ID}`));
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during profile get", async () => {
|
||||
vi.mocked(prisma.player.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await app.fetch(new Request(`http://localhost/profile/${DISCORD_ID}`));
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("includes completed story chapters in profile response", async () => {
|
||||
const state = makeState({
|
||||
story: {
|
||||
@@ -256,5 +268,23 @@ describe("profile route", () => {
|
||||
const body = await res.json() as { profileSettings: { numberFormat: string } };
|
||||
expect(body.profileSettings.numberFormat).toBe("suffix");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during profile update", async () => {
|
||||
vi.mocked(prisma.player.update).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await put({
|
||||
characterName: "NewName",
|
||||
profileSettings: { numberFormat: "suffix" },
|
||||
});
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during profile update", async () => {
|
||||
vi.mocked(prisma.player.update).mockRejectedValueOnce("raw string error");
|
||||
const res = await put({
|
||||
characterName: "NewName",
|
||||
profileSettings: { numberFormat: "suffix" },
|
||||
});
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -92,6 +92,18 @@ describe("transcendence route", () => {
|
||||
expect(body.newTranscendenceCount).toBe(1);
|
||||
expect(body.echoes).toBeGreaterThanOrEqual(0);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during transcendence", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post("");
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during transcendence", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post("");
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /buy-upgrade", () => {
|
||||
@@ -149,5 +161,17 @@ describe("transcendence route", () => {
|
||||
expect(body.echoesRemaining).toBe(95); // 100 - 5
|
||||
expect(body.purchasedUpgradeIds).toContain("echo_income_1");
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws during buy-upgrade", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce(new Error("DB error"));
|
||||
const res = await post("/buy-upgrade", { upgradeId: "echo_income_1" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
|
||||
it("returns 500 when the database throws a non-Error value during buy-upgrade", async () => {
|
||||
vi.mocked(prisma.gameState.findUnique).mockRejectedValueOnce("raw string error");
|
||||
const res = await post("/buy-upgrade", { upgradeId: "echo_income_1" });
|
||||
expect(res.status).toBe(500);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user