Skip to content

Commit

Permalink
feat(front): enhance api error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Lerri-Cofannos committed Oct 9, 2023
1 parent 0b5e7b9 commit d98311e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
13 changes: 10 additions & 3 deletions front/src/app/api/tags/route.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { getErrorMessage } from "@/app/helpers/getErrorMessage";
import { TagsData } from "@/services/prisma/TagsData";
import { NextResponse } from "next/server";

export const GET = async (): Promise<NextResponse> => {
try {
const tags = await TagsData.getTags();
return NextResponse.json({ tags });
} catch (err) {
return NextResponse.json({ error: "failed to fetch tags from prisma" });
return NextResponse.json({ tags }, { status: 200 });
} catch (err: unknown) {
const message = getErrorMessage(err);
return NextResponse.json(
{
error: `failed to fetch tags from prisma: ${message}`,
},
{ status: 500 },
);
}
};
26 changes: 26 additions & 0 deletions front/src/app/helpers/getErrorMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
type ErrorWithMessage = {
message: string;
};

const isErrorWithMessage = (error: unknown): error is ErrorWithMessage => {
return (
typeof error === "object" &&
error !== null &&
"message" in error &&
typeof (error as Record<string, unknown>).message === "string"
);
};

const toErrorWithMessage = (maybeError: unknown): ErrorWithMessage => {
if (isErrorWithMessage(maybeError)) return maybeError;

try {
return new Error(JSON.stringify(maybeError));
} catch {
return new Error(String(maybeError));
}
};

export const getErrorMessage = (error: unknown): string => {
return toErrorWithMessage(error).message;
};

0 comments on commit d98311e

Please sign in to comment.