Search code examples
node.jsexpresshttp-status-code-404

is there a proper way to handle status for error validation?


Im learning Backend using nodejs Im completely beginner just a noob question.

I send status code 400 for every validation error and I noticed the console it log a lot of error every request. is this a correct way to do it ? or should I put 200+ status?

enter image description here

 export const signup = async (req, res) => {
  const { email, name, password } = req.body;

  try {
    if (!email || !name || !password) {
      throw new Error("All fields are Required!");
    }

    const userAlreadyExists = await User.findOne({ email });
    if (userAlreadyExists) {
      return res
        .status(400)
        .json({ success: "Failed!", message: "User Already Exist!" });
    }

    //hash the password
    const hashedPassword = await bcryptjs.hash(password, 10);
    //verification code for sending in the email!
    const verification = generateVerificationCode();

    const user = new User({
      email,
      password: hashedPassword,
      name,
      verification,
      verificationTokenExpiresAt: Date.now() + 24 * 60 * 60 * 1000, // 24hours
    });

    await user.save();

    //jtw Token
    generateTokenAndSetCookies(res, user._id);
    //email Send to the new User
    // await nodeEmailVerification(email, verification);

    res.status(201).json({
      success: true,
      message: "User Created Successfully",
      user: {
        ...user._doc,
        password: undefined,
      },
    });
  } catch (error) {
    return res.status(400).json({ success: false, message: error.message });
  }
};

Solution

  • It is correct to use the 400 status code, but it is wrong to use the 400 status code for all error cases. The 400 status code is used for validation errors or malformed requests where required fields are missing. However, catch handles all error cases like server side errors etc, so we need to return 500 status code from catch. That is, you should use the correct status code for all error cases, such as 400 (Bad Request), 404 (Not Found), and 500 (Internal Server Error). In this case, you can handle it on the frontend side to avoid showing all errors in the browser console. Instead of logging errors to the browser, you can show error messages to the user based on the error case.

    I updated your code with correct status code.

    export const signup = async (req, res) => {
      const { email, name, password } = req.body;
    
      try {
        // Here, you will validate params so will return status 400 code
        if (!email || !name || !password) {
          return res.status(400).json({ success: false, message: "All fields are required!" });
        }
    
        const userAlreadyExists = await User.findOne({ email });
        if (userAlreadyExists) {
          return res
            .status(400)
            .json({ success: false, message: "User already exists!" });
        }
    
        const hashedPassword = await bcryptjs.hash(password, 10);
        const verification = generateVerificationCode();
    
        const user = new User({
          email,
          password: hashedPassword,
          name,
          verification,
          verificationTokenExpiresAt: Date.now() + 24 * 60 * 60 * 1000, // 24 hours
        });
    
        await user.save();
    
        generateTokenAndSetCookies(res, user._id);
    
        res.status(201).json({
          success: true,
          message: "User created successfully",
          user: {
            ...user._doc,
            password: undefined,
          },
        });
      } catch (error) {
        // Here, you will handle server-side errors and will return status 500 code
        return res.status(500).json({ success: false, message: "Server error: " + error.message });
      }
    };
    

    To get more understanding about the status code, please check here