Skip to content

Commit 9ce8b9d

Browse files
committed
Fix error handling
1 parent 799308e commit 9ce8b9d

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/app/api/users/route.test.ts

+11-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { expect, test } from "@jest/globals";
55
import { dbMock } from "@/test/dbMock";
66
import { authMock } from "@/test/authMock";
77
import { UserType } from "@prisma/client";
8+
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
89

910
test("returns 401 on unauthenticated requests", async () => {
1011
await testApiHandler({
@@ -146,8 +147,16 @@ test("user already exists", async () => {
146147
});
147148

148149
dbMock.user.create.mockImplementation(() => {
149-
throw new Error();
150-
})
150+
throw new PrismaClientKnownRequestError(
151+
'violates uniqueness constraint',
152+
{
153+
code: 'P2002',
154+
clientVersion: 'mock',
155+
meta: {},
156+
batchRequestIdx: 1
157+
}
158+
);
159+
});
151160

152161
const res = await fetch({ method: "POST", body: getGoodFormData() });
153162
await expect(res.status).toEqual(409);

src/app/api/users/route.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { UserType } from "@prisma/client";
55
import { NextRequest, NextResponse } from "next/server";
66
import { zfd } from "zod-form-data";
77
import * as argon2 from 'argon2';
8+
import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
89

910
const ALLOWED_USER_TYPES: UserType[] = [
1011
UserType.ADMIN,
@@ -79,8 +80,13 @@ export async function POST(req: NextRequest) {
7980
type: userInvite.userType
8081
}
8182
});
82-
} catch {
83-
return conflictError("User already exists");
83+
} catch (e) {
84+
if (e instanceof PrismaClientKnownRequestError) {
85+
if (e.code === 'P2002') {
86+
return conflictError("User already exists");
87+
}
88+
}
89+
throw e;
8490
}
8591
return ok();
8692
}

0 commit comments

Comments
 (0)