Socket
Socket
Sign inDemoInstall

prisma-better-errors

Package Overview
Dependencies
0
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    prisma-better-errors

This module provides a way to handle errors thrown by the [Prisma ORM](https://www.prisma.io/) in a more descriptive way. By default, Prisma throws errors with error codes that can be hard to understand for developers not familiar with the specific error


Version published
Maintainers
1
Install size
31.7 kB
Created

Changelog

Source

1.0.4

Patch Changes

  • 2a1bcdd: Fixed Issue #2 \n added github actions

Readme

Source

Prisma Better Errors

This module provides a way to handle errors thrown by the Prisma ORM in a more descriptive way. By default, Prisma throws errors with error codes that can be hard to understand for developers not familiar with the specific error codes used by Prisma. This module maps Prisma error codes to error messages and HTTP status codes, making it easier for developers to understand what went wrong and return appropriate error responses in their APIs.

Installation

You can install this module using npm:

npm install prisma-better-errors

Usage

To use this module, you need to import the prismaError class and use it to catch Prisma errors in your code. Here's an example:

import { PrismaClient,Prisma } from '@prisma/client';
import {  prismaError } from './prisma';

const prisma = new PrismaClient();

async function main() {
  try {
    const user = await prisma.user.create({
      data: {
        name: 'Alice',
        email: 'alice@prisma.io',
      },
    });
    console.log(user);
  } catch (error:any) {
    if (error instanceof Prisma.PrismaClientKnownRequestError) {
      console.log('HERE');
      throw new prismaError(error);
    }
    throw error
  }
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });
}

In this example, the getUser function tries to fetch a user from the database using Prisma's findUnique method. If an error is thrown, the prismaError class is used to wrap the error and provide a more descriptive error message and HTTP status code.

The prismaError class extends the built-in Error class and adds three properties:

  • message: the error message.
  • statusCode: the HTTP status code to return in the API response.
  • metaData (optional): an object containing additional metadata about the error. This can be useful for debugging purposes.

With express middleware

Add the prismaError class to your error handling middleware and return the statusCode and title properties as part of the API error response. The metaData property can also be returned if it contains any additional information about the error.

app.use((err, req, res, next) => {
  if (err instanceof prismaError) {
    res.status(err.statusCode).json({
      title: err.title,
      message: err.message,
      metaData: err.metaData,
    });
  } else {
    // Handle other errors here
  }
});

// response
{
    "title": "Prisma Error",
    "statusCode": 409,
    "message": "Unique constraint failed",
    "metaData": {
        "target": [
            "email"
        ]
    }
}


Custom Error Messages

You can customize the error message and HTTP status code for each Prisma error code by modifying the QueryError map in the prisma-better-errors module. For example:

import { QueryError, prismaError } from 'prisma-better-errors';

// Add a new error code mapping
QueryError.set('P3000', { message: 'My custom error message', httpStatus: 422 });

// Use the new error code in your code
try {
  // Prisma code here
} catch (error) {
  // these are the query errors
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    throw new prismaError(error);
  }
}

Error Codes

The following table lists the error codes and their corresponding error messages and HTTP status codes:

Error CodeMessageHTTP Status Code
P2000The provided value for the column is too long for the column's type400
P2001The record searched for in the where condition does not exist404
P2002Unique constraint failed409
P2003Foreign key constraint failed409
P2004A constraint failed on the database400
P2005The value stored in the database for the field is invalid for the field's type400
P2006The provided value for the field is not valid400
P2007Data validation error400
P2008Failed to parse the query400
P2009Failed to validate the query400
P2010Raw query failed500
P2011Null constraint violation400
P2012Missing a required value400
P2013Missing a required argument400
P2014The change you are trying to make would violate the required relation400
P2015A related record could not be found404
P2016Query interpretation error400
P2017The records for relation between the parent and child models are not connected400
P2018The required connected records were not found404
P2019Input error400
P2020Value out of range for the type400
P2021The table does not exist in the current database404
P2022The column does not exist in the current database404
P2023Inconsistent column data400
P2024Timed out fetching a new connection from the pool500
P2025An operation failed because it depends on one or more records that were required but not found404
P2026The current database provider doesn't support a feature that the query used400
P2027Multiple errors occurred on the database during query execution500

Author

Youssef Hany

Check out my portfolio

Keywords

FAQs

Last updated on 11 Mar 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc