Hello @Michel2025
To ensure that all products are added to the cart except the ones that trigger errors like “out of stock,” “draft product,” or “variant not found,” you can modify your JavaScript code to handle each product individually. Instead of stopping the entire process when one product fails, you can process each product separately and catch the errors for each one. Here’s a general approach you can follow:
Approach:
-
Loop through the products: For each product, you try to add it to the cart.
-
Error handling: If the product has an error (like being out of stock or a draft product), catch the error and skip adding that product to the cart.
-
Continue with other products: Continue processing the remaining products, even if one fails.
Example JavaScript Code:
function addProductsToCart(products) {
let errors = []; // To store products that fail
let successfulAdds = 0; // To track the successful additions
// Loop through each product and try adding it to the cart
products.forEach(product => {
addProductToCart(product)
.then(response => {
successfulAdds++;
console.log(`Product ${product.id} added successfully.`);
})
.catch(error => {
errors.push({ product: product, error: error });
console.log(`Error adding product ${product.id}: ${error.message}`);
});
});
// After all products are processed, log the results
setTimeout(() => {
console.log(`${successfulAdds} products added to the cart.`);
if (errors.length > 0) {
console.log('Failed to add the following products:');
errors.forEach(err => console.log(`Product ${err.product.id} failed due to: ${err.error.message}`));
}
}, 1000); // Adjust time if needed based on your network latency or number of products
}
function addProductToCart(product) {
return new Promise((resolve, reject) => {
// Your logic to add the product to the cart
// This example assumes you're using Shopify's AJAX API to add the product
let formData = {
items: [
{
id: product.variantId,
quantity: product.quantity
}
]
};
fetch('/cart/add.js', {
method: 'POST',
body: JSON.stringify(formData),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => {
if (data.status && data.status === 404) {
reject(new Error('Variant not found'));
} else if (data.status && data.status === 422) {
reject(new Error('Out of stock'));
} else if (data.status && data.status === 500) {
reject(new Error('Product is a draft'));
} else {
resolve(data);
}
})
.catch(err => reject(err));
});
}
Explanation:
. addProductsToCart(products): This function processes the list of products and attempts to add each one to the cart. If there’s an error, it catches the error and logs it.
. addProductToCart(product): This function attempts to add a single product to the cart using Shopify’s /cart/add.js API. It returns a promise that resolves if the product is added successfully or rejects with an error message if it fails (e.g., variant not found, out of stock, or product is a draft).
. The loop ensures that all products are processed, and even if one fails, the rest will still be added.
Error Handling:
. The catch block inside the forEach ensures that the script continues executing even if a product fails to add to the cart.
. reject(new Error(‘Variant not found’)) and other similar errors are triggered when certain conditions (like the product being out of stock or not found) occur.
This approach should allow products to be added to the cart independently, even if some fail due to issues like those you mentioned.
Thank you 