Next.js Discord

Discord Forum

Questions about error handling in Nextjs

Answered
Sun bear posted this in #help-forum
Open in Discord
Avatar
Sun bearOP
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 !
Answered by joulev
Throw an error if it is unexpected (meaning there is a bug in the code). Errors thrown == 500 errors.

Return an object/response detailing the failure if that is a user error (meaning the code is not buggy, just the user didn’t send the correct request).

In your case it should be a returned response and not a throw new Error statement.
View full answer

5 Replies

Avatar
Throw an error if it is unexpected (meaning there is a bug in the code). Errors thrown == 500 errors.

Return an object/response detailing the failure if that is a user error (meaning the code is not buggy, just the user didn’t send the correct request).

In your case it should be a returned response and not a throw new Error statement.
Answer
Avatar
Sun bearOP
Okay, that's what I thought, so I send back a response and depending on its status, I either display a message describing the user error in the client, for example? and if the response is ok, I redirect the user.
I think NextResponse is the right class for this, then?
Avatar
Sounds good
Avatar
Sun bearOP
Okay thank you very much, i really needed some advice on this