Best way to handle errors
Hi, what is the best way to handle errors or non-existent values, like, is this case im blindly updating an record where the id is the id of the project, in the case of the id does not exist, prisma throw an P2025 error, that i can handle it on a try catch and return that no record has found, and nothing has been updated.
Or the other way, i can first make an query to find the project, and if he exist, i update it.
What is the common way, or the best way to use on this cases?
1 Reply
Skipping coffee for instant knowledge! Let's brew that AI answer now.
The best practice for handling updates on potentially non-existent records in Prisma is to use a try/catch block around your update operation and specifically handle the P2025 error code, which Prisma throws when the record to update does not exist. This approach avoids the need for an extra query (like findUnique) and keeps your code efficient and concise.
Here’s how you can do it:
This is the recommended approach by the Prisma team, as the update operation will always throw if the record does not exist, and handling it via try/catch is both efficient and idiomatic in Prisma. Doing a pre-check with a separate query is not necessary and can be less efficient, especially if you have many such operations to perform. If you want a more reusable solution, you can wrap this logic in a helper function or use a custom extension as shown in some community workarounds, but the core idea remains the same: catch and handle P2025 errors gracefully Best method to delete records without raising exceptions if they dont exist Allow Nested delete or disconnect to Skip If Relation Does Not Exist.
If you want an update operation that never throws when the record does not exist, you can use updateMany, but note that it returns a count, not the updated record, and is less idiomatic for single-record updates.
✅ Great, thanks for letting us know that this solved your question!