Zend framework 2 recommended way for error handling

前端 未结 1 1754
太阳男子
太阳男子 2020-12-23 17:45

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 ca

相关标签:
1条回答
  • 2020-12-23 18:33

    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...
    }
    
    0 讨论(0)
提交回复
热议问题