Handling Prisma Errors
1. Catching PrismaClientKnownRequestError
import { Prisma } from "@prisma/client";
try { await prisma.user.create({ data }); }
catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {
if (e.code === "P2002") return { error: "Email already exists" };
}
throw e;
}
| Aspect | Detail |
| Class | PrismaClientKnownRequestError |
| code | P2xxx error code |
| meta | Extra context (target field, etc.) |
2. Handling Unique Constraint Errors
| Code | Meaning |
| P2002 | Unique constraint violation |
| meta.target | Field(s) that conflicted |
3. Handling Foreign Key Errors
| Code | Meaning |
| P2003 | FK constraint failed |
| P2014 | Required relation violation |
| P2025 | Record to connect not found |
4. Handling Record Not Found Errors
| API | Detail |
findUnique | Returns null |
findUniqueOrThrow | Throws P2025 |
update | Throws P2025 if not found |
5. Handling Validation Errors
| Class | Detail |
| PrismaClientValidationError | Invalid query shape (TS-checked at compile) |
| Cause | Often dynamic input bypassed types |
6. Implementing Error Logging
prisma.$on("error", (e) => logger.error({ msg: e.message, target: e.target }));
| Source | Detail |
| log: ["error"] | Emit error events |
| Sentry | Capture with context |
7. Using Error Codes
| Code | Meaning |
| P2000 | Value too long |
| P2002 | Unique constraint |
| P2003 | Foreign key constraint |
| P2024 | Pool timeout |
| P2025 | Record not found |
| P2034 | Transaction conflict (retry) |
8. Implementing Custom Error Classes
export class NotFoundError extends Error {
constructor(public entity: string, public id: string | number) {
super(`${entity} ${id} not found`);
}
}
| Benefit | Detail |
| Domain layer | Decouple from Prisma codes |
| HTTP mapping | Single translator at boundary |
9. Handling Transaction Errors
| Code | Detail |
| P2028 | Transaction API error |
| P2034 | Serialization failure — retry |
| Tip | Wrap interactive tx in retry loop |
10. Implementing Error Recovery Strategies
| Strategy | When |
| Retry | Transient (P1001, P2024, P2034) |
| Compensating action | Saga / outbox patterns |
| Fail fast | Validation / 4xx errors |