Skip to content

Commit

Permalink
Merge branch 'main' into feat/api/notify-newcomer
Browse files Browse the repository at this point in the history
  • Loading branch information
wiyco authored Nov 25, 2024
2 parents 71fe615 + 1dd0e7e commit e1e714e
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/lib/api/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { NextResponse } from "next/server";
import { z } from "zod";

export class APIError extends Error {
constructor(
message: string,
public status: number = 400,
public code?: string
) {
super(message);
this.name = "APIError";
}
}

export function handleAPIError(error: unknown) {
if (error instanceof APIError) {
return NextResponse.json(
{
error: {
message: error.message,
code: error.code,
},
},
{ status: error.status }
);
}

if (error instanceof z.ZodError) {
return NextResponse.json(
{
error: {
message: "入力値が不正です",
details: error.errors,
},
},
{ status: 400 }
);
}

console.error(error);
return NextResponse.json(
{ error: { message: "サーバーエラーが発生しました" } },
{ status: 500 }
);
}
2 changes: 2 additions & 0 deletions src/lib/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./error";
export * from "./response";
14 changes: 14 additions & 0 deletions src/lib/api/response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NextResponse } from "next/server";

export type APIResponse<T> = {
data: T;
status: number;
};

export function createAPIResponse<T>(data: T): APIResponse<T> {
return { data, status: 200 };
}

export function handleAPISuccess<T>(data: T) {
return NextResponse.json(createAPIResponse(data));
}
1 change: 1 addition & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./api";
export * from "./swr";

0 comments on commit e1e714e

Please sign in to comment.