Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda