Skip to content

Commit 8500af5

Browse files
committed
feat: display friendly error messages on API failure
Closes #34
1 parent 60c8f15 commit 8500af5

1 file changed

Lines changed: 28 additions & 9 deletions

File tree

app/api/compare/route.ts

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,38 @@ import { calculateUserScore } from "../../../lib/score";
44

55
export const runtime = "nodejs";
66

7+
function classifyError(error: any): { message: string; status: number } {
8+
const msg = error?.message ?? "";
9+
10+
if (msg === "User not found") {
11+
return { message: "GitHub user not found. Please check the username and try again.", status: 404 };
12+
}
13+
14+
if (msg.includes("rate limit") || error?.status === 403) {
15+
return {
16+
message: "GitHub API rate limit exceeded. Please wait a few minutes and try again.",
17+
status: 429,
18+
};
19+
}
20+
21+
if (msg.includes("Bad credentials") || error?.status === 401) {
22+
return { message: "GitHub API authentication error. Please contact the administrator.", status: 500 };
23+
}
24+
25+
if (error?.code === "ENOTFOUND" || error?.code === "ETIMEDOUT") {
26+
return { message: "Unable to reach GitHub. Please check your connection and try again.", status: 503 };
27+
}
28+
29+
return { message: "Something went wrong while fetching data. Please try again later.", status: 500 };
30+
}
31+
732
export async function GET(request: Request) {
833
const { searchParams } = new URL(request.url);
934
const usernames = searchParams.getAll("username");
1035

1136
if (usernames.length === 0) {
1237
return NextResponse.json(
13-
{ success: false, error: "provide at least one username param" },
38+
{ success: false, error: "Please provide at least one GitHub username." },
1439
{ status: 400 }
1540
);
1641
}
@@ -36,13 +61,7 @@ export async function GET(request: Request) {
3661
return NextResponse.json({ success: true, users: results });
3762
} catch (error: any) {
3863
console.error("GitHub score error:", error);
39-
const message =
40-
error?.message === "User not found"
41-
? "GitHub user not found"
42-
: "Failed to calculate score";
43-
return NextResponse.json(
44-
{ success: false, error: message },
45-
{ status: 500 }
46-
);
64+
const { message, status } = classifyError(error);
65+
return NextResponse.json({ success: false, error: message }, { status });
4766
}
4867
}

0 commit comments

Comments
 (0)