0

So I have managed to get rudimentary add to cart links working from external sources. Using the following sources:

Official & out of date Wiki

This StackOverflow post

Here is the working code

As long as the item is in the database, and is in stock, then it works. However as soon as you try to add an item that doesn't exist, or an item is out of stock, one of a number of errors are thrown:

Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'This product is currently out of stock.' in /var/www/domain.com/app/Mage.php:595 Stack trace: #0 /var/www/domain.com/app/code/core/Mage/Checkout/Model/Cart.php(284): Mage::throwException('This product is...') #1 /var/www/domain.com/add-to-cart.php(50): Mage_Checkout_Model_Cart->addProduct('2', '1') #2 {main} thrown in /var/www/domain.com/app/Mage.php on line 595

Since there seems to be other people having issues with adding out of stock products to the cart, how can I catch this error either outside of or inside of magento and then continue to the cart? With error printing disabled the script just returns a blank white page and does nothing.

1 Answer 1

2

I think you just have to surround the problematic code in your script with a try catch block and do whatever you want to do in the catch block:

try {
    $cart->addProduct($id, $qty);
    $session->setCartWasUpdated(true);
    $cart->save();
} catch (Exception $e) {
    // do whatever you want to do when product cannot be added
    header("Location: ". Mage::helper('checkout/cart')->getCartUrl());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.