Tuesday 17 June 2014

Magento How to throw specific exceptions

The call Mage::throwException() is used to throw exceptions of the specific Mage_Core_Exception variety. These are generally used to show error messages to the end user.

Sometimes a basic Exception just isn't specific enough to catch the problem responsibly so you can deal with the issue. If you're writing a custom module and you tend to wrap your code in try and catch blocks, convention would insist you use Mage::throwException().

Mage::throwException is essentially a wrapper for Mage_Core_Exception($message) with the additional functionality of being able to add the exception to a session via a getSingleton call chained with addMessage

Type hinting your catch blocks with specific Exceptions allows you to deal with each specific issue separately,
you might have something like this in your controller action:

try {
        try {
            if (!Zend_Validate::is(trim($_FILES['attachment']['name']), 'NotEmpty')) {
                $error = true;
            }
        } catch (Exception $e) {
            $error = true;
        }
        if ($error) {
            Mage::throwException('error message');
        }

    } catch (Exception $e) {
        $translate->setTranslateInline(true);              
        $errorMsg = $e->getMessage() ? $e->getMessage() : 'Unable to submit your request. Please, try again later';
        Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__($errorMsg));
        $this->_redirect('*/*/');
        return;
    }


Best of luck

No comments:

Post a Comment