Nest.js | Filter Pengecualian Prisma
Jan 20 2023
Di Nest.js, Anda dapat membuat filter pengecualian untuk menangani pengecualian tertentu yang mungkin terjadi di aplikasi Anda.
Di Nest.js, Anda dapat membuat filter pengecualian untuk menangani pengecualian tertentu yang mungkin terjadi di aplikasi Anda. Untuk membuat filter pengecualian, Anda dapat menggunakan @UseFilters()dekorator dan mengirimkan instance kelas yang mengimplementasikan antarmuka ExceptionFilter. Kelas harus memiliki catch()metode yang mengambil contoh pengecualian yang dilemparkan dan objek ExecutionContext.
Misalnya, Anda dapat membuat kelas HttpExceptionFilteryang mengimplementasikan ExceptionFilterantarmuka:
import { ExceptionFilter, Catch, HttpException } from '@nestjs/common';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, context: ExecutionContext) {
// Handle the exception here
}
}
@UseFilters(new HttpExceptionFilter())
@Controller()
export class MyController {
// ...
}
@UseFilters(new HttpExceptionFilter())
@Get()
async findAll() {
// ...
}
@Catch(MyException)
export class MyExceptionFilter implements ExceptionFilter {
catch(exception: MyException, context: ExecutionContext) {
// Handle the exception here
}
}
Misalnya, Anda dapat membuat kelas PrismaExceptionFilteryang mengimplementasikan ExceptionFilterantarmuka:
import {
ArgumentsHost,
Catch,
HttpException,
HttpServer,
HttpStatus,
} from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Prisma } from '@prisma/client';
export type ErrorCodesStatusMapping = {
[key: string]: number;
};
/**
* {@link PrismaClientExceptionFilter}
* catches {@link Prisma.PrismaClientKnownRequestError}
* and {@link Prisma.NotFoundError} exceptions.
*/
@Catch(Prisma?.PrismaClientKnownRequestError, Prisma?.NotFoundError)
export class PrismaClientExceptionFilter extends BaseExceptionFilter {
/**
* default error codes mapping
*
* Error codes definition for Prisma Client (Query Engine)
* @see https://www.prisma.io/docs/reference/api-reference/error-reference#prisma-client-query-engine
*/
private errorCodesStatusMapping: ErrorCodesStatusMapping = {
P2000: HttpStatus.BAD_REQUEST,
P2002: HttpStatus.CONFLICT,
P2025: HttpStatus.NOT_FOUND,
};
/**
* @param applicationRef
* @param errorCodesStatusMapping
*/
constructor(
applicationRef?: HttpServer,
errorCodesStatusMapping?: ErrorCodesStatusMapping,
) {
super(applicationRef);
if (errorCodesStatusMapping) {
this.errorCodesStatusMapping = Object.assign(
this.errorCodesStatusMapping,
errorCodesStatusMapping,
);
}
}
/**
* @param exception
* @param host
* @returns
*/
catch(
exception: Prisma.PrismaClientKnownRequestError | Prisma.NotFoundError | any,
host: ArgumentsHost,
) {
if (exception instanceof Prisma.PrismaClientKnownRequestError) {
return this.catchClientKnownRequestError(exception, host);
}
if (exception instanceof Prisma.NotFoundError) {
return this.catchNotFoundError(exception, host);
}
}
private catchClientKnownRequestError(
exception: Prisma.PrismaClientKnownRequestError,
host: ArgumentsHost,
) {
const statusCode = this.errorCodesStatusMapping[exception.code];
const message = `[${exception.code}]: ${this.exceptionShortMessage(exception.message)}`;
if (!Object.keys(this.errorCodesStatusMapping).includes(exception.code)) {
return super.catch(exception, host);
}
super.catch(new HttpException({ statusCode, message }, statusCode), host);
}
private catchNotFoundError(
{ message }: Prisma.NotFoundError,
host: ArgumentsHost,
) {
const statusCode = HttpStatus.NOT_FOUND;
super.catch(new HttpException({ statusCode, message }, statusCode), host);
}
private exceptionShortMessage(message: string): string {
const shortMessage = message.substring(message.indexOf('→'));
return shortMessage
.substring(shortMessage.indexOf('\n'))
.replace(/\n/g, '')
.trim();
}
}
{
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(
new AllExceptionsFilter(),
new PrismaClientExceptionFilter(httpAdapter),
);
}
{
const { httpAdapter } = app.get(HttpAdapterHost);
app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter, {
P2022: HttpStatus.BAD_REQUEST,
}));
}
Taylor Sheridan Baru Menambahkan 1 Bintang 'Yellowstone' Favoritnya ke Pemeran 'Lawmen: Bass Reeves'

![Apa itu Linked List? [Bagian 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































