// ✅ 正确:区分客户端和服务器错误
app.post('/api/orders', (req, res) => {
const { productId, quantity, email } = req.body;
// 验证错误是客户端问题(4xx)
const validationErrors = [];
if (!email || !email.includes('@')) {
validationErrors.push("Invalid email format");
}
if (!quantity || quantity <= 0) {
validationErrors.push("Quantity must be positive");
}
if (validationErrors.length > 0) {
return res.status(400).json({
error: "Validation failed",
details: validationErrors
});
}
try {
const order = createOrder({ productId, quantity, email });
res.status(201).json(order); // 201用于资源创建
} catch (error) {
// 只有实际的服务器错误才返回500
console.error('Order creation failed:', error);
res.status(500).json({
error: "Internal server error"
});
}
});