DEV Community

Nurul Islam Rimon
Nurul Islam Rimon

Posted on

1 1 1 1 1

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

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong Β· web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌢️πŸ”₯

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay