Here's my problem: I've been kicking myself for a few days now over Nextjs' error handling. Even in general, in fact, I don't really know how to go about it.
Basically, I've got a login form made with shadcn/ui, i.e. with client-side and server-side zod validation via safeParse().
Here's my code for the login actions:
export async function onLoginAction(
state: LoginFormState,
data: FormData
): Promise<LoginFormState> {
const userEntries = Object.fromEntries(data);
const parsedValidation = loginSchema.safeParse(userEntries);
if (!parsedValidation.success) {
return {
...state,
fields: userEntries,
errors: parsedValidation.error.flatten().fieldErrors,
};
}
const { email, password } = parsedValidation.data;
try {
const response = await login(email, password);
const body = await response.json();
console.log(body);
return {
fields: userEntries,
errors: {},
success: false,
message: body.message,
};
} catch (error) {
console.log("error: ", error);
return {
fields: userEntries,
errors: {},
success: false,
message: "Strange error.",
};
}
}
export async function login(email: string, password: string) {
const user = await prisma.user.findUnique({
where: {
email: email,
},
});
if (!user) {
return NextResponse.json(
{ message: "This account does not exist." },
{ status: 404 }
);
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return NextResponse.json(
{ message: "Invalid password." },
{ status: 401 }
);
}
const session = await createSession(user.id);
console.log(session);
if (!session) {
return NextResponse.json(
{ message: "There was an error creating session." },
{ status: 500 }
);
}
return NextResponse.json({ status: 200 });
}
Don't pay too much attention to the quality of the code, it's a bit trashy because I was in the middle of testing stuff. So I was wondering: should I throw errors when, for example, the email doesn't correspond to any user account, or should I raise a NextResponse containing an appropriate message, a status, like I already do?
If people could pass on best practices to a self-taught noob like me, that would be great, because I'm struggling.
Thanks !