DEV Community

Nurul Islam Rimon
Nurul Islam Rimon

Posted on

1 1 1 1 2

Are you worried of Prisma Errors? Here are all the prisma error formatted!πŸ“ƒ

I have created it Injectable. You can use this functionally also.

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { Injectable } from '@nestjs/common';
import {
  PrismaClientInitializationError,
  PrismaClientKnownRequestError,
  PrismaClientRustPanicError,
  PrismaClientValidationError,
} from '@prisma/client/runtime/library';

interface ErrorMessage {
  path: string;
  message: string;
}

@Injectable()
export class PrismaExceptionFormatter {
  formatPrismaError(exception: PrismaClientKnownRequestError): ErrorMessage[] {
    const errorMessages: ErrorMessage[] = [];

    switch (exception.code) {
      case 'P2002':
        errorMessages.push({
          path: exception.meta?.target?.[0] || 'unknown_field',
          message: `A record with this ${exception.meta?.target?.[0]} already exists.`,
        });
        break;
      case 'P2003':
        errorMessages.push({
          path: (exception.meta?.field_name as string) || 'unknown_relation',
          message: `Invalid reference: ${exception.meta?.field_name as string}.`,
        });
        break;
      case 'P2005': // Invalid value
      case 'P2006': // Invalid format
        errorMessages.push({
          path: (exception.meta?.field_name as string) || 'unknown_field',
          message: `Invalid value for ${exception.meta?.field_name as string}.`,
        });
        break;
      case 'P2025': // Record not found
        errorMessages.push({
          path: (exception.meta?.model_name as string) || 'resource',
          message: `The requested ${exception.meta?.model_name as string} does not exist.`,
        });
        break;
      default:
        errorMessages.push({
          path: 'unknown_error',
          message: exception.message || 'An unknown Prisma error occurred.',
        });
    }

    return errorMessages;
  }

  formatQueryError(
    exception: PrismaClientValidationError | PrismaClientRustPanicError,
  ): ErrorMessage[] {
    return [
      {
        path: 'query',
        message: exception.message || 'Invalid query or database error.',
      },
    ];
  }

  formatInitializationError(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    exception: PrismaClientInitializationError,
  ): ErrorMessage[] {
    return [
      {
        path: 'database',
        message: 'Failed to connect to the database.',
      },
    ];
  }

  formatUnknownError(exception: any): ErrorMessage[] {
    return [
      {
        path: 'unknown',
        // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
        message: exception?.message || 'An unexpected Prisma error occurred.',
      },
    ];
  }

  formatError(exception: any): ErrorMessage[] {
    if (exception instanceof PrismaClientKnownRequestError) {
      return this.formatPrismaError(exception);
    } else if (
      exception instanceof PrismaClientValidationError ||
      exception instanceof PrismaClientRustPanicError
    ) {
      return this.formatQueryError(exception);
    } else if (exception instanceof PrismaClientInitializationError) {
      return this.formatInitializationError(exception);
    } else {
      return this.formatUnknownError(exception);
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Regards,
N I Rimon

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay