Nest.js | Prisma-Ausnahmefilter
Jan 20 2023
In Nest.js können Sie einen Ausnahmefilter erstellen, um bestimmte Ausnahmen zu behandeln, die in Ihrer Anwendung auftreten können.
In Nest.js können Sie einen Ausnahmefilter erstellen, um bestimmte Ausnahmen zu behandeln, die in Ihrer Anwendung auftreten können. Um einen Ausnahmefilter zu erstellen, können Sie den @UseFilters()Dekorator verwenden und eine Instanz einer Klasse übergeben, die die ExceptionFilterSchnittstelle implementiert. Die Klasse sollte über eine catch()Methode verfügen, die eine Instanz der ausgelösten Ausnahme und ein ExecutionContextObjekt aufnimmt.
Sie können beispielsweise eine Klasse erstellen HttpExceptionFilter, die die Schnittstelle implementiert ExceptionFilter:
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
}
}
Sie können beispielsweise eine Klasse erstellen PrismaExceptionFilter, die die Schnittstelle implementiert ExceptionFilter:
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,
}));
}

![Was ist überhaupt eine verknüpfte Liste? [Teil 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)



































