Skip to content

Commit

Permalink
Handle ZodError
Browse files Browse the repository at this point in the history
  • Loading branch information
demanguillaume committed May 23, 2024
1 parent 9d2a35a commit c083dce
Showing 1 changed file with 59 additions and 2 deletions.
61 changes: 59 additions & 2 deletions src/app/utils/errorHandlerUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ import {
NotFoundException,
InternalServerErrorException,
} from "@/types/exceptions";
import { ZodError } from "zod";
import {
ZodError,
ZodInvalidEnumValueIssue,
ZodInvalidLiteralIssue,
ZodInvalidStringIssue,
ZodInvalidTypeIssue,
ZodIssueCode,
ZodTooBigIssue,
ZodTooSmallIssue,
ZodUnrecognizedKeysIssue,
} from "zod";

/**
* @params error: any
Expand All @@ -17,8 +27,10 @@ export function handleException(error: any) {
console.error("An error occurred:", error);

switch (true) {
case error instanceof BadRequestException:
case error instanceof ZodError:
const formattedMessage = formatZodErrors(error);
return NextResponse.json({ message: formattedMessage }, { status: 400 });
case error instanceof BadRequestException:
return NextResponse.json({ message: error.message }, { status: 400 });
case error instanceof UnauthorizedException:
return NextResponse.json({ message: error.message }, { status: 401 });
Expand All @@ -35,3 +47,48 @@ export function handleException(error: any) {
);
}
}

function formatZodErrors(error: ZodError): string {
return error.errors
.map((e) => {
const path = e.path.join(" -> ");
let message = `Error at ${path}: ${e.message}`;

// Handle specific issue types
switch (e.code) {
case ZodIssueCode.invalid_type:
const invalidTypeIssue = e as ZodInvalidTypeIssue;
message += ` (expected ${invalidTypeIssue.expected}, received ${invalidTypeIssue.received})`;
break;
case ZodIssueCode.invalid_literal:
const invalidLiteralIssue = e as ZodInvalidLiteralIssue;
message += ` (expected ${invalidLiteralIssue.expected}, received ${invalidLiteralIssue.received})`;
break;
case ZodIssueCode.too_small:
const tooSmallIssue = e as ZodTooSmallIssue;
message += ` (minimum ${tooSmallIssue.minimum}, inclusive: ${tooSmallIssue.inclusive})`;
break;
case ZodIssueCode.too_big:
const tooBigIssue = e as ZodTooBigIssue;
message += ` (maximum ${tooBigIssue.maximum}, inclusive: ${tooBigIssue.inclusive})`;
break;
case ZodIssueCode.invalid_enum_value:
const enumIssue = e as ZodInvalidEnumValueIssue;
message += ` (expected one of: ${enumIssue.options.join(
", "
)}, received: ${enumIssue.received})`;
break;
case ZodIssueCode.unrecognized_keys:
const keysIssue = e as ZodUnrecognizedKeysIssue;
message += ` (unrecognized keys: ${keysIssue.keys.join(", ")})`;
break;
case ZodIssueCode.invalid_string:
const stringIssue = e as ZodInvalidStringIssue;
message += ` (validation: ${stringIssue.validation})`;
break;
}

return message;
})
.join("; ");
}

0 comments on commit c083dce

Please sign in to comment.