-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(front): enhance api error handling
- Loading branch information
1 parent
0b5e7b9
commit d98311e
Showing
2 changed files
with
36 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }, | ||
); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}; |