Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support custom error message mappings #73

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 64 additions & 19 deletions lib/prisma-client-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ import { Prisma } from '@prisma/client';
export declare type GqlContextType = 'graphql' | ContextType;

export type ErrorCodesStatusMapping = {
Copy link
Contributor Author

@megane42 megane42 Aug 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I concern that this type is no longer ErrorCodesStatusMapping strictly, because it handles not only "Status" but also "Message" now. Currently I haven't renamed it now, because it's hard to rename the already exported type.

[key: string]: number;
[key: string]:
| number
| {
statusCode?: number;
errorMessage?: string;
};
};

/**
Expand All @@ -26,19 +31,21 @@ export class PrismaClientExceptionFilter extends BaseExceptionFilter {
* 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 = {
private readonly defaultMapping = {
P2000: HttpStatus.BAD_REQUEST,
P2002: HttpStatus.CONFLICT,
P2025: HttpStatus.NOT_FOUND,
};

private readonly userDefinedMapping?: ErrorCodesStatusMapping;

/**
* @param applicationRef
* @param errorCodesStatusMapping
*/
constructor(
applicationRef?: HttpServer,
errorCodesStatusMapping: ErrorCodesStatusMapping | null = null,
errorCodesStatusMapping?: ErrorCodesStatusMapping,
) {
super(applicationRef);

Expand All @@ -51,12 +58,15 @@ export class PrismaClientExceptionFilter extends BaseExceptionFilter {
// P2022: HttpStatus.BAD_REQUEST,
// }));
//
if (errorCodesStatusMapping) {
this.errorCodesStatusMapping = Object.assign(
this.errorCodesStatusMapping,
errorCodesStatusMapping,
);
}
// or
//
// const { httpAdapter } = app.get(HttpAdapterHost);
// app.useGlobalFilters(new PrismaClientExceptionFilter(httpAdapter, {
// // You can omit either statusCode or errorMessage so that the default one is used.
// P2022: { statusCode: HttpStatus.BAD_REQUEST, errorMessage: "bad request" },
// }));
//
this.userDefinedMapping = errorCodesStatusMapping;
}

/**
Expand All @@ -72,12 +82,16 @@ export class PrismaClientExceptionFilter extends BaseExceptionFilter {
exception: Prisma.PrismaClientKnownRequestError,
host: ArgumentsHost,
) {
const statusCode = this.errorCodesStatusMapping[exception.code];
const statusCode =
this.userDefinedStatusCode(exception) ||
this.defaultStatusCode(exception);

const message =
`[${exception.code}]: ` + this.exceptionShortMessage(exception.message);
this.userDefinedExceptionMessage(exception) ||
this.defaultExceptionMessage(exception);

if (host.getType() === 'http') {
if (!Object.keys(this.errorCodesStatusMapping).includes(exception.code)) {
if (statusCode === undefined) {
return super.catch(exception, host);
}

Expand All @@ -87,20 +101,51 @@ export class PrismaClientExceptionFilter extends BaseExceptionFilter {
);
} else if (host.getType<GqlContextType>() === 'graphql') {
// for graphql requests
if (!Object.keys(this.errorCodesStatusMapping).includes(exception.code)) {
if (statusCode === undefined) {
return exception;
}

return new HttpException({ statusCode, message }, statusCode);
}
}

private exceptionShortMessage(message: string): string {
const shortMessage = message.substring(message.indexOf('→'));
return shortMessage
.substring(shortMessage.indexOf('\n'))
.replace(/\n/g, '')
.trim();
private userDefinedStatusCode(
exception: Prisma.PrismaClientKnownRequestError,
): number | undefined {
const userDefinedValue = this.userDefinedMapping?.[exception.code];
return typeof userDefinedValue === 'number'
? userDefinedValue
: userDefinedValue?.statusCode;
}

private defaultStatusCode(
exception: Prisma.PrismaClientKnownRequestError,
): number | undefined {
return this.defaultMapping[exception.code];
}

private userDefinedExceptionMessage(
exception: Prisma.PrismaClientKnownRequestError,
): string | undefined {
const userDefinedValue = this.userDefinedMapping?.[exception.code];
return typeof userDefinedValue === 'number'
? undefined
: userDefinedValue?.errorMessage;
}

private defaultExceptionMessage(
exception: Prisma.PrismaClientKnownRequestError,
): string {
const shortMessage = exception.message.substring(
exception.message.indexOf('→'),
);
return (
`[${exception.code}]: ` +
shortMessage
.substring(shortMessage.indexOf('\n'))
.replace(/\n/g, '')
.trim()
);
}
}

Expand Down