How to catch exceptions in your ZF2 controllers?

I installed ZendSkeletonApplication using ZF 2.0.3 and I cannot catch exceptions in my controllers. For example, if I put the code below in module/Application/src/Application/Controller/IndexController.php :

 public function indexAction() { echo "BEFORE\n"; try { throw new \Exception("My exception"); } catch (Exception $e) { echo "Caught exception $e\n"; exit; } 

and access the page that I get:

 BEFORE An error occurred An error occurred during execution; please try again later. Additional information: Exception File: module/Application/src/Application/Controller/IndexController.php:25 Message: My exception 

ViewModel fires and displays an exception, which actually prevents me from catching it.

How can I catch exceptions in ZF2 controllers?

+8
php exception try-catch zend-framework2
source share
1 answer

You throw a PHP generic exception

 throw new \Exception("My exception"); 

but you will catch an exception from the current namespace

 } catch (Exception $e) { 

Assuming your controller is in Application\Controller , you need to declare

 use \Exception; 

above your class, import a global exception into the current namespace or

 } catch (\Exception $e) { 

to catch a global PHP exception.

+33
source share

All Articles