Click here to Skip to main content
15,885,278 members
Articles
(untagged)

Zend Framework 2: Error & Exception Handling

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
24 Jan 2015CPOL2 min read 13.8K   1   3
Zend Framework 2: Error & Exception Handling

Hello everyone, today I am going to share one problem I faced when I was developing my first project with Zend Framework 2. The issue was with defining and managing error, exceptions. In the front-end, it was displaying errors/exceptions to the user, rather filing it into any file. It was too awkward for a user to see the error message as kind of paragraph in the front-end :D.

So, that time, I thought of logging those errors/exceptions in a log file, for further check and fix for the issue, as we always do with any other framework/normal PHP projects. I searched for the native solution, it is present or not in the same Framework. I found the manual (though now-a-days we can find a lot of blogs/tutorials for solving error logging issue), where some logging code has been written, and which I thought would definitely help me to reach my goal.

So, what I did was – I just went through the manual for error logging once, and believe me, I didn’t understand even 50% of the concept :). That’s why I decided be patient and go through the same manual once again or twice.

Hmmm… after reading 3 more times, I got some points and I thought of using it in the code. Then, I checked and analyzed what should be the best position to use the logger code, so that it would help me as extent and I should not have to write the same code again and again.

So, here I am going to explain what attempt I had taken that time and it was successful also. Let’s check the step by step process of adding the logger for errors/exception.

First Step

First, attach to the dispatch error event inside Module.php (say in Application folder).

PHP
public function onBootstrap(MvcEvent $e)
{
    // other config code

    $sm = $e->getApplication()->getServiceManager();
    $sharedManager = $e->getApplication()->getEventManager()->getSharedManager();

    $sharedManager->attach('Zend\Mvc\Application', 'dispatch.error',
        function($e) use ($sm) {
            if ($e->getParam('exception')) {
                $sm->get('\Zend\Log\Logger')->crit($e->getParam('exception'));
                return false;
            }
        }
    );
}

Second Step

Create service.config.php file (say Application/config/service.config.php).

PHP
return array(
    'factories' => array(
        // other config code ,
        '\Zend\Log\Logger' => function($sm){
            $logger = new Zend\Log\Logger;
            $writer = new Zend\Log\Writer\Stream('./data/logs/' . date('Y-m-d') . '-error.log');

            $logger->addWriter($writer);
            return $logger;
        },
    ),
);

Now, it’s done. The call anyway will go through bootstrap method and will log the error if any into one file. The path we used above for creating the log is inside ‘data/logs/’ directory. Do you really find it useful? :) If yes, then please like and add some comments, if you want.

Thanks :) and I will be happy to hear from you :).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Software engineer with around 6 years of web application development experience in open source technologies like PHP, MySQL, HTML, HTML5, CSS, CSS3, Javascript, jQuery etc.

I love to learn and share my knowledge in which manner I can and like to solve the issues as in the coding perspective. I am an active contributor in community forums like StackOverflow, CodeProject etc. Besides that, I write blogs in free time and speak in various technical community events.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Volynsky Alex25-Jan-15 8:12
professionalVolynsky Alex25-Jan-15 8:12 
GeneralRe: My vote of 5 Pin
Prava-MFS25-Jan-15 18:32
professionalPrava-MFS25-Jan-15 18:32 
GeneralRe: My vote of 5 Pin
Volynsky Alex26-Jan-15 10:36
professionalVolynsky Alex26-Jan-15 10:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.