#Questions about error handling in Nextjs

7 messages · Page 1 of 1 (latest)

crisp plaza
#

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 !

scarlet wharfBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

glossy tangle
crisp plaza
#

I think NextResponse is the right class for this, then?

glossy tangle
#

Sounds good

crisp plaza
#

Okay thank you very much, i really needed some advice on this