CRUD Operations
findUniqueOrThrow
Get a record by unique field or throw
Retrieve a record by its primary key or unique field, or throw an error if not found.
try {
const user = await client.user.findUniqueOrThrow({
where: { id: userId },
});
console.log(user.name); // Guaranteed to exist
} catch (error) {
console.error("User not found");
}Return Type
Returns the record or throws an error:
const user: User = await client.user.findUniqueOrThrow({
where: { id: userId },
});
// Type is User, not User | nullCompare with findUnique which returns null if not found.
By Primary Key
const user = await client.user.findUniqueOrThrow({
where: { id: userId },
});
// Throws if user doesn't existBy Unique Field
const user = await client.user.findUniqueOrThrow({
where: { email: "alice@example.com" },
});Composite Unique Keys
For composite unique constraints:
const post = await client.post.findUniqueOrThrow({
where: {
slug_boardId: {
slug: "hello-world",
boardId: "board-123",
},
},
});Error Handling
try {
const user = await client.user.findUniqueOrThrow({
where: { id: invalidId },
});
} catch (error) {
// Thrown if not found
console.error("User does not exist");
}Use Cases
Guaranteed Lookups
When the record must exist:
const user = await client.user.findUniqueOrThrow({
where: { id: userId },
});
// No null check needed
console.log(user.name);Fail-Fast Patterns
Throw immediately if preconditions aren't met:
async function updateTodo(todoId: string, data: any) {
const todo = await client.todo.findUniqueOrThrow({
where: { id: todoId },
});
const board = await client.board.findUniqueOrThrow({
where: { id: todo.boardId },
});
// Both records guaranteed to exist
return await client.todo.update({
where: { id: todoId },
data,
});
}Permissions Validation
const todo = await client.todo.findUniqueOrThrow({
where: { id: todoId },
});
if (todo.userId !== currentUserId) {
throw new Error("Access denied");
}Selection and Relations
const user = await client.user.findUniqueOrThrow({
where: { id: userId },
select: { id: true, name: true, email: true },
});
const userWithProfile = await client.user.findUniqueOrThrow({
where: { id: userId },
include: { profile: true },
});Performance
Same performance characteristics as findUnique - fast index-based lookup:
const user = await client.user.findUniqueOrThrow({
where: { id: userId }, // O(1) lookup
});Type Safety
The return type is never null:
const user = await client.user.findUniqueOrThrow({
where: { id: userId },
});
// No null check needed
console.log(user.name); // ✅ Safe
// Type system prevents null checks
if (user === null) {
// Redundant check - always false (may trigger linter warnings)
// ...
}See Also
- findUnique - Returns null if not found
- findFirstOrThrow - First matching with throw
- findFirst - Returns null if not found