0

I created my own extension and within my own controller. Now I want to catch exceptions occuring in one of my actions and write it to my own log file. But try() catch does not seem to work. It just outputs the stack to the browser.

public function testAction() {
    try {
      error();
    } catch(Exception $exception) {
        logMessage();
    }
}
1

Modifying my answer in light of finding out it's Magento 1.x

It would be helpful for you to show us the actual output of you error however you are catching the error effectively.

Have you tried putting a die into your catch ? How is your exception being thrown ? What is the contents logMessage() method.

It really should just be as simple as doing the following :

public function testAction() {
    try {
      error();
    } catch(Exception $exception) {
        Mage::log($e, null, 'my-custom-file.log', true);
    }
}

You could also try catching the error this way

public function testAction() {
    try {
      error();
    } catch (Mage_Core_Exception $e) {
       Mage::log($e, null, 'my-custom-file.log', true);
    } catch(Exception $exception) {
        Mage::log($e, null, 'my-custom-file.log', true);
    }
}

As the semantics would suggest you can only catch an error that has been thrown. You can't catch a fatal error.

Using your question as an example :

public function testAction() {
    try {
      $this->doingSomething();
    } catch(Exception $exception) {
        Mage::log($e, null, 'my-custom-file.log', true);
    }
}

protected function doSomething() {
    if (!method_exists($this, 'error') {
        Mage::throwException('Method error() is not defined');
    } else {
        return true;
    }
}
  • I am asking about Magento v1.9. I think your answer is Magento 2 specific? Also I don't want to capture a particulary exception but rather any possible exception. – alobeejay Aug 15 '17 at 13:19
  • I am doing exactly your first example. I am calling a function error() which does not exist. And instead of going into the catch block I get the output "Fatal error: Call to undefined function error() " – alobeejay Aug 15 '17 at 14:43
  • You can only catch an exception if an exception is thrown. e.g. Mage::throwException('Some Message'); or throw new Exception('Some Message'); – Frank Aug 15 '17 at 15:30
  • Magento handle this for observers like this : #File: app/code/core/Mage/Core/Model/App.php protected function _callObserverMethod($object, $method, $observer) { if (method_exists($object, $method)) { $object->$method($observer); } elseif (Mage::getIsDeveloperMode()) { Mage::throwException('Method "'.$method.'" is not defined in "'.get_class($object).'"'); } return $this; } – Frank Aug 15 '17 at 15:30
  • I updated my answer to clarify. – Frank Aug 21 '17 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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