Catching db exceptions and logging

1,280 views
Skip to first unread message

Mariusz Łączak

unread,
Jan 16, 2013, 8:53:46 AM1/16/13
to pha...@googlegroups.com
Hi,

How to catch db exceptions to the log file? In the bootstrap I have something like this:

try {

    //Register an autoloader
    $loader = new \Phalcon\Loader();
    $loader->registerDirs(array(
        '../app/controllers/',
        '../app/models/'
    ))->register();

    //Create a DI
    $di = new Phalcon\DI\FactoryDefault();

    //Set the database service
    $di->set('db', function(){
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "secret",
            "dbname" => "test_db"
        ));
    });

    //Setting up the view component
    $di->set('view', function(){
        $view = new \Phalcon\Mvc\View();
        $view->setViewsDir('../app/views/');
        return $view;
    });

    //Handle the request
    $application = new \Phalcon\Mvc\Application();
    $application->setDI($di);
    echo $application->handle()->getContent();

catch(\Phalcon\Exception $e)
{
    $logger = new \Phalcon\Logger\Adapter\File('../app/logs/'.date('Ymd').'.log', array(
        'mode' => 'a+'
    ));
    $logger->error(get_class($e). '['.$e->getCode().']: '. $e->getMessage());
    $logger->info($e->getFile().'['.$e->getLine().']');
    $logger->debug("Trace: \n".$e->getTraceAsString()."\n");
    $logger->close();
}

But if in query is something wrong I see Internal Server Error and message does not appends to file. If another exception occurs, then it is OK.

Regards,
Mariusz

Nikolaos Dimopoulos

unread,
Jan 16, 2013, 9:01:09 AM1/16/13
to pha...@googlegroups.com

Have a look at the incubator repo. Wojtek has submitted an Error handler class that does all the heavy lifting for you.

Also look at this bootstrap file

https://github.com/niden/phalcon-angular-harryhogfootball/blob/master/app/library/NDN/Bootstrap.php

The initDatabase function has code to log every query and I follow a similar approach to Wojtek's with my own error class handler.

--
You received this message because you are subscribed to the Google Groups "Phalcon PHP Framework" group.
To post to this group, send email to pha...@googlegroups.com.
To unsubscribe from this group, send email to phalcon+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/phalcon/-/hztcCG6idAsJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Mariusz Łączak

unread,
Jan 16, 2013, 9:27:33 AM1/16/13
to pha...@googlegroups.com
A lot of useful things.

Thanks Nikolaos
Reply all
Reply to author
Forward
0 new messages