Fail-fast resource lookup
An API endpoint requires a matching resource and maps missing resources to an exception response.
Prisma · Module
findFirstOrThrow returns the first record matching a query and throws PrismaClientKnownRequestError when no record is found. Its result type is non-nullable.
Call the model method with the same query arguments as findFirst. Prisma returns the first matching record, but when no record matches it throws a PrismaClientKnownRequestError; the returned type is non-nullable, so callers do not need a null check.
prisma.<model>.findFirstOrThrow(<args>)| Name | Type | Description |
|---|---|---|
args | FindFirstArgs<Model> | Arguments for the model's findFirst query, including filtering, ordering, pagination, relation loading, and field selection options. |
The first matching record with a non-nullable type; throws PrismaClientKnownRequestError when no record is found.
const user = await prisma.user.findFirstOrThrow({
where: { email: "alice@prisma.io" },
orderBy: { id: "asc" },
});
console.log(user.email);Looks up the first matching user and throws instead of returning null when no match exists.
An API endpoint requires a matching resource and maps missing resources to an exception response.
A script or job should stop when a required database record is absent.
A query needs the first item from an ordered set and absence is invalid.
findFirstOrThrow retrieves one record using the same criteria as findFirst. If no record matches, it throws a PrismaClientKnownRequestError rather than returning null.
Follow-up: How does its type differ from findFirst? Its return type is non-nullable, which removes the need for a null check after a successful call.
It accepts the query arguments used by findFirst, such as where, orderBy, select, and include. The query returns the first record matching those criteria.
Follow-up: How can ordering affect the selected record? Supplying orderBy makes which matching record is first explicit instead of relying on an unspecified order.
Use it when absence should cause the operation to fail and the caller already handles exceptions. It is useful for routes and scripts that want fail-fast behavior instead of branching on null.
Follow-up: When should findFirst be preferred? Use findFirst when no match is an expected outcome that the application should handle as a nullable result.
findFirstfindUniqueOrThrowPrismaClientKnownRequestError