Reputation: 1943
I noticed that the Skeleton Application that Zend provides does not handle error 500
. I know that in ZF1 there was an ErrorController
that took care of that. I have done some research online, but did not find a clear cut solution for this.
So what is the best way for error handling in ZF2. Would it be on per module basis or some global exception/error handler?
I know that another solution would be to add ini_set('display_errors', true);
to my index.php
, but I don't really like that solution. It seems that the framework should provide some way for handling errors.
Upvotes: 15
Views: 16381
Reputation: 1688
You can handle the exceptions in anyway you want after catching it as the following example in which you are catching the exception globally...:
In the onBootstrap
method in your Module.php
you can attach a function to execute when an event occurs, the following attach a function to be executed when an error (exception) is raised:
public function onBootstrap(MvcEvent $e)
{
$application = $e->getApplication();
$em = $application->getEventManager();
//handle the dispatch error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'handleError'));
//handle the view render error (exception)
$em->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER_ERROR, array($this, 'handleError'));
}
and then define the function to handle the error in any way you want, the following is an example:
public function handleError(MvcEvent $e)
{
//get the exception
$exception = $e->getParam('exception');
//...handle the exception... maybe log it and redirect to another page,
//or send an email that an exception occurred...
}
Upvotes: 31