Tillitsdone
down Scroll to discover

Error Handling and Custom Messages in Zod

Learn how to implement robust error handling and custom error messages using Zod in Node.js applications.

Master data validation with practical examples and best practices.
thumbnail

Abstract fluid art with flowing patterns in bright turquoise and golden yellow colors representing data validation and error handling shot from top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

If you’re building Node.js applications, data validation is crucial for maintaining application reliability. Zod has emerged as a powerful schema validation library, but its true strength lies in its error handling capabilities. Let’s dive into how we can leverage Zod to create robust error handling with meaningful error messages.

Understanding Zod’s Error Structure

When Zod encounters validation errors, it provides detailed information about what went wrong. By default, these errors might be too technical for end-users. Here’s how we can make them more user-friendly:

import { z } from 'zod';
const userSchema = z.object({
username: z.string()
.min(3, 'Username must be at least 3 characters')
.max(20, 'Username cannot exceed 20 characters'),
email: z.string()
.email('Please provide a valid email address'),
age: z.number()
.min(18, 'You must be at least 18 years old')
});

Geometric abstract composition with interconnected clean lines in bright neon green and off-white colors representing structured data flow captured from 45-degree angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Implementing Custom Error Messages

Custom error messages make your application more user-friendly. Let’s explore different ways to customize error messages:

const orderSchema = z.object({
items: z.array(z.object({
productId: z.string(),
quantity: z.number().positive()
})).nonempty({
message: "Your cart cannot be empty"
}),
shippingAddress: z.string().min(10, {
message: "Please provide a complete shipping address"
})
}).refine(
(data) => data.items.length <= 10,
{ message: "Maximum 10 items allowed per order" }
);

Handling Errors in Express.js

Here’s how we can integrate Zod validation with Express.js middleware:

const validateRequest = (schema: z.ZodSchema) => {
return async (req: Request, res: Response, next: NextFunction) => {
try {
const validatedData = await schema.parseAsync(req.body);
req.body = validatedData;
next();
} catch (error) {
if (error instanceof z.ZodError) {
return res.status(400).json({
status: 'error',
errors: error.errors.map(err => ({
field: err.path.join('.'),
message: err.message
}))
});
}
next(error);
}
};
};

Modern minimalist architectural detail with clean curves and lines in warm walnut and iron colors showing structural integrity photographed from low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Advanced Error Handling Patterns

Sometimes you need more complex validation rules. Zod’s refinements and transformations can help:

const passwordSchema = z.string()
.min(8, "Password must be at least 8 characters")
.refine(
(password) => {
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
return hasUpperCase && hasLowerCase && hasNumber;
},
{
message: "Password must contain uppercase, lowercase, and number"
}
);

Error handling doesn’t have to be complicated. With Zod, you can create clear, consistent, and user-friendly error messages that make your application more professional and maintainable.

Smooth waves of liquid metal in bright silver and umber colors symbolizing smooth error handling flow captured from bird's eye view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.