How can i hande errors nextjs + prisma
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
I still dont understand where should i write my error handling logic
i have api folder where i am write prisma queries
then i am using fetch in some specifi function and then
i use react to handle this data
i have api folder where i am write prisma queries
then i am using fetch in some specifi function and then
i use react to handle this data
6 Replies
Sun bearOP
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";
function getUserById(id: string) {
return prisma.user.findUnique({
where: {
id: id,
},
});
}
export async function GET(
request: Request,
{ params }: { params: { id: string } }
) {
try {
const user = await getUserById(params.id);
if (!user) {
return NextResponse.json({ error: "User not found." }, { status: 404 });
}
return NextResponse.json({ user });
} catch (error) {
return NextResponse.json(
{ error: "Could not fetch user." },
{ status: 500 }
);
}
}
export async function DELETE(
request: Request,
{ params }: { params: { id: string } }
) {
try {
let user = await getUserById(params.id);
if (!user) {
return NextResponse.json({ error: "User not found." }, { status: 404 });
}
user = await prisma.user.delete({
where: {
id: params.id,
},
});
return NextResponse.json({ user });
} catch (error) {
return NextResponse.json(
{ error: "Could not delete user." },
{ status: 500 }
);
}
}
export async function PUT(
request: Request,
{ params }: { params: { id: string } }
) {
const { name } = (await request.json()) as {
name: string;
};
try {
let user = await getUserById(params.id);
if (!user) {
return NextResponse.json({ error: "User not found." }, { status: 404 });
}
user = await prisma.user.update({
where: {
id: params.id,
},
data: {
name,
},
});
return NextResponse.json({ user });
} catch (error) {
return NextResponse.json(
{ error: "Could not update user." },
{ status: 500 }
);
}
}i dont think this code is good
how can i improve it
i mean i dont like that i write try catch in 3 places
on api, on function and on client
The first try-cath block is not really necessary. Prisma won't throw an error if there’s no data.
But to be safe in case something else happens you can move the try-catch logic directly inside your
But to be safe in case something else happens you can move the try-catch logic directly inside your
getUserById function to avoid repeating it every time you need to use that function.