Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
How to get ZodError in json

I'm trying to get zod validation errors in json when i test it in insomnia, but am getting it only in terminal and in insomnia it's telling me Error: Couldn't connect to server i saw some examples and everywhere it's worked... don't understand why it's not working...

my register method

export const register = async (req: Request, res: Response) => {
  const payloadSchema = z
    .object({
      firstname: z.string({
        required_error: "Firstname is required",
        invalid_type_error: "Title must be a string",
      }),
      lastname: z.string({
        required_error: "Lastname is required",
        invalid_type_error: "Title must be a string",
      }),
      email: z
        .string({ required_error: "Email is required" })
        .email({ message: "Invalid email address" }),
      password: z.string(),
      confirm: z.string(),
    })
    .refine((data) => data.password === data.confirm, {
      message: "Passwords don't match",
      path: ["confirm"], 
    });

  const parsedData = await payloadSchema.parseAsync(req.body);

  try {
    const result = await User.findOne({ where: { email: parsedData.email } });

    if (result) {
      return res.status(400).json({
        success: false,
        error: "User already exists",
      });
    }

    const user = new User();
    user.firstname = parsedData.firstname;
    user.lastname = parsedData.lastname;
    user.email = parsedData.email;
    user.password = parsedData.password;
    await user.save();

    const accessToken = jwt.sign(
      { userId: user.id },
      process!.env!.TOKEN_SECRET!
    );

    return res.status(200).json({
      success: true,
      createdUser: user,
      accessToken: accessToken,
    });
  } catch (e) {
    if (e instanceof ZodError) {
      return res.status(400).json({
        success: false,
        error: e.flatten(),
      });
    } else if (e instanceof Error) {
      return res.status(400).json({
        message: e.message,
      });
    }
  }
};

so what's am doing wrong, and how can i fix it? thanks for attention.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

const parsedData = await payloadSchema.parseAsync(req.body);

The parseAsync call from Zod will throw an error if the validation fails, but in your code it's outside the try/catch block, try moving it inside:

try {
  const parsedData = await payloadSchema.parseAsync(req.body);
 
  const result = await User.findOne({ where: { email: parsedData.email } });

  ...
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!