Search code examples
phperror-handlingsymfony1symfony-1.4

Handling MySQL errors from Symfony application


I wish to know what is the best method to handle MySQL exceptions from a Symfony application, less said for example this one from normal enviroment(not dev):

Oops! An Error Occurred The server returned a "500 Internal Server Error".

which translate at _dev as follow:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '343434' for key 'rut'

how do yours handle with this kind of errors in order to show a message to end users or something more friendly?


Solution

  • Your best bet is to make a custom error page, and optionally create a custom error handler to alert you of the error.

    First, create a custom error page, just create a file in /path/to/project/config/error/error.html.php. Symfony will automatically use your error page instead of its own if it exists.

    If you want to get a bit more advanced, you can add an event listener to handle uncaught exceptions. To do this, edit /path/to/project/config/ProjectConfiguration.class.php and add a listener like so:

    class ProjectConfiguration extends sfProjectConfiguration
    {
      public function setup()
      {
        //...
        $this->dispatcher->connect('application.throw_exception', array($this, 'listenToException'));
      }
    
      public function listenToException(sfEvent $event)
      {
        $handler = new myExceptionHandler($event);
        $handler->doSomethingHere();
      }
    }
    

    Then, all you have to do is create your own myExceptionHandler class that excepts an sfEvent $event parameter. You can do whatever you want in here, I prefer to send an email to myself to tell me that an error has occurred.

    Here is a brief example:

    class myExceptionHandler
    {
      protected $event;
    
      public function __construct(sfEvent $event)
      {
        $this->event = $event;
      }
    
      protected function getMailer()
      {
        return sfContext::getInstance()->getMailer();
      }
    
      public function notify()
      {
        $subject = 'Uncaught Exception';
        $body = $this->event->getSubject();
    
        $mailer = $this->getMailer();
        $mailer->composeAndSend('root@yourserver.com', 'you@youremail.com', $subject, $body);
      }
    }
    

    In this example, you would just call $handler->notify() from your project configuration and it would email you the stack trace. You could also include other information like $_SERVER variables etc...