Exercise 2: Handling P2002 and P2025 — Possible Solution ========================================================== // users.ts import { prisma } from "./lib/prisma"; import { Prisma } from "./generated/prisma/client"; export async function registerUser(email: string, name: string) { try { const user = await prisma.user.create({ data: { email, name } }); return `Welcome, ${user.name}!`; } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") { return "That email is already registered."; } throw e; // anything else is a real problem } } export async function recordView(slug: string) { try { return await prisma.post.update({ where: { slug }, data: { viewCount: { increment: 1 } }, }); } catch (e) { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2025") { return null; // no post with that slug } throw e; } } Why this approach: - Catching the database's own error, rather than checking "does this email exist?" first, avoids a race: two sign-ups could both pass a check and then one would still fail. The unique constraint is the real guarantee. - Only the expected codes are handled; everything else is re-thrown, so real bugs aren't hidden. - increment is atomic, so simultaneous views are all counted. WHY THIS WORKS AS AN ANSWER ------------------------------ It handles the two most common error codes precisely, re-throws anything unexpected, and explains why relying on the database's constraint is safer than checking first.