Prisma - Transaction Operations and Error Handling
Prisma - Transaction Operations and Error Handling

Prisma - Transaction Operations and Error Handling

in
  1. Transaction Handling
    1. Using Transactions
  2. Error Handling
  3. References

In the previous post, we introduced Prisma as a modern ORM solution for TypeScript and demonstrated how to perform basic CRUD operations. In this article, we will dive deeper into how to use Prisma for basic transaction operations and error handling.

Transaction Handling

When performing update operations, it is crucial to ensure data consistency and integrity. Prisma supports transaction operations, allowing you to execute multiple database actions as a single atomic operation.

Using Transactions

The following example demonstrates how to execute multiple operations in a transaction to ensure that they either all succeed or all fail. If any of the operations fail, the entire transaction will be rolled back, ensuring the database does not end up in an inconsistent state.

async function transactionalUpdateAndDelete() {
  const [updatedUser, deletedPost] = await prisma.$transaction([
    prisma.user.update({
      where: { email: 'bob@example.com' },
      data: { name: 'Bob Transaction' },
    }),
    prisma.post.delete({
      where: { id: 2 },
    }),
  ])
  
  console.log('User updated in transaction:', updatedUser)
  console.log('Post deleted in transaction:', deletedPost)
}

transactionalUpdateAndDelete()
  .catch(e => {
    throw e
  })
  .finally(async () => {
    await prisma.$disconnect()
  })

After executing the code, it returns the error: An operation failed because it depends on one or more records that were required but not found. Record to delete does not exist.

This occurs because the post ID being deleted does not exist. In this case, you will notice that Bob’s name was not changed either.

After modifying the post ID and deleting it correctly, the execution result is as follows:

User updated in transaction: { id: 9, name: 'Bob Transaction', email: 'bob@example.com' }
Post deleted in transaction: {
  id: 9,
  title: 'My First Post',
  content: 'This is the content',
  published: true,
  authorId: 9
}

Error Handling

When performing update or delete operations, you may encounter various errors such as missing records or unique constraint violations. Prisma provides rich error information to help developers debug and handle errors properly.

async function safeDeleteUser() {
  try {
    const deletedUser = await prisma.user.delete({
      where: { email: 'nonexistent@example.com' },
    })
    console.log('Deleted user:', deletedUser)
  } catch (error) {
    if (error.code === 'P2025') {
      console.error('The record does not exist and cannot be deleted.')
    } else {
      console.error('An error occurred while deleting the user:', error)
    }
  } finally {
    await prisma.$disconnect()
  }
}

safeDeleteUser()

When executed, if you attempt to delete a non-existent user, the output will be:

The record does not exist and cannot be deleted.

With this, the introduction to Prisma is essentially complete. In real-world development, combining and using these operations properly will greatly improve the performance and reliability of your application.

References