Skip to content

Commit cedb54c

Browse files
committed
fix(webapp): read Prisma initialization error codes from errorCode
PrismaClientInitializationError carries its code on errorCode, not code, so connection failures such as P1001 were counted as unknown. Those are the failures this counter most needs to name.
1 parent 2df2377 commit cedb54c

2 files changed

Lines changed: 31 additions & 4 deletions

File tree

apps/webapp/app/utils/dbMetrics.server.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,26 @@ describe("dbMetrics", () => {
109109
expect(pointFor(all, "db.client.operation.duration", "create")).toBeDefined();
110110
});
111111

112+
it("reads errorCode for initialization errors, which do not carry code", async () => {
113+
const failure = Object.assign(new Error("Can't reach database server"), {
114+
errorCode: "P1001",
115+
});
116+
117+
await expect(
118+
recordOperation(
119+
{ datasource: "replica", client: "run-ops-new" },
120+
"findFirst",
121+
"TaskRun",
122+
() => Promise.reject(failure)
123+
)
124+
).rejects.toThrow("Can't reach database server");
125+
126+
const point = pointFor(await collect(), "db.client.operation.errors", "findFirst");
127+
128+
expect(point).toBeDefined();
129+
expect(point!.attributes["db.error_code"]).toBe("P1001");
130+
});
131+
112132
it("labels a non-Prisma error as unknown rather than dropping the count", async () => {
113133
await expect(
114134
recordOperation({ datasource: "writer", client: "control-plane" }, "update", "TaskRun", () =>

apps/webapp/app/utils/dbMetrics.server.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,18 @@ function getInstruments(): Instruments {
6262
*/
6363
const includeModel = process.env.DB_METRICS_INCLUDE_MODEL === "1";
6464

65+
/**
66+
* Prisma splits the error code across two property names: `PrismaClientKnownRequestError`
67+
* carries `code`, while `PrismaClientInitializationError` carries `errorCode`. Both are
68+
* worth labelling, and the initialization codes are the connection failures (P1001 and
69+
* friends) this counter most needs to surface, so check `code` first and fall back.
70+
*/
6571
function errorCode(error: unknown): string {
66-
if (typeof error === "object" && error !== null && "code" in error) {
67-
const code = (error as { code: unknown }).code;
68-
if (typeof code === "string") {
69-
return code;
72+
if (typeof error === "object" && error !== null) {
73+
const candidate =
74+
(error as { code?: unknown }).code ?? (error as { errorCode?: unknown }).errorCode;
75+
if (typeof candidate === "string") {
76+
return candidate;
7077
}
7178
}
7279
return "unknown";

0 commit comments

Comments
 (0)