question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Help developers better handle SQL errors

See original GitHub issue

Problem

We sometimes want to handle SQL errors differently to return a proper error to the frontend. For example, we might want to display email already used if a unique violation is detected on the field. The current situation is that we have to check against an obscure error code (P2002 for example for unique validation failure) and then go into meta.target to get which field broke. Its never easy to extract meaningful stuff from ORM(-like) tools despite being a very common operation and I think it could be a factor of differentiation for prisma.

Propositions

I see two possible way of dealing more gracefully with that:

  1. Create more custom error types in javascript and use instanceof to catch them. This would look like:
      try {
        const user = await prisma.user.create({ data });
        return res.status(204).send();
      } catch (err) {
        if (err instanceof PrismaUniqueViolationError) {
          return res.status(400).send('DUPLICATE EMAIL');
        }
        return res.status(400).send('BAD REQUEST');
      }
    
  2. Create an enum of errors. This would look like
      try {
        const user = await prisma.user.create({ data });
        return res.status(204).send();
      } catch (err) {
        if (err.code === PrismaErrors.UniqueViolation) {
          return res.status(400).send('DUPLICATE EMAIL');
        }
        return res.status(400).send('BAD REQUEST');
      }
    

I also think there should be helpers to extract the problematic fields from the error. Something like:

if (err.code === PrismaErrors.UniqueViolation) {
    const duplicateFields = extractErrorFields(err);
    return res.status(400).json({ code: 'unique_violation', fields: duplicateFields});
}

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:135
  • Comments:16 (5 by maintainers)

github_iconTop GitHub Comments

53reactions
steebchencommented, Jun 8, 2020

If possible, I’d like to have something like this which I’ve initially proposed in prisma/prisma-client-js#720:

try {
  await db.users.insert(newUser)
} catch (err) {
  if (err instanceof UniqueConstraintViolation) {
    // not sure if typescript can infer the error, but I think it can
    if (err.field == "email") {
      console.log("user already exists with this email")
      return
    }
    console.log("unique constraint violation on another field: " + err.field)
  }
}
31reactions
ayush-goyalcommented, Apr 2, 2021

Any updates on the status of this?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to implement error handling in SQL Server - SQLShack
This article explains how to implement SQL error handling using the SQL server try-catch statement and what can be done in general when...
Read more >
10 Handling PL/SQL Errors
To handle unexpected Oracle errors, you can use the OTHERS handler. Within this handler, you can call the functions SQLCODE and SQLERRM to...
Read more >
Most T-SQL Queries Don't Even Try to Handle Errors.
IMHO, SQL Server does a great job with error handling all on it's own and (usually) doesn't need anything extra in the form...
Read more >
Sql server error handling best practices
The best way to improve your programme would be capturing all sql errors and store them in a SQL table, that will help...
Read more >
Avoiding a Jurassic problem - 7 tips for handling errors, before ...
As developers you should be alerted when something is going wrong and be able to see details to help you track down and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found