How to handle errors in services.php

Hi, In my project i have a Plugin (Error) where i capture all exception, and show a page 500..

class ErrorPlugin extends Plugin {
  public function beforeException($event, $dispatcher, $exception) {
    $this->view->setLayout('error');
    $dispatcher->forward(array(
      "controller" => "errors",
      "action" => "show500",
      "params" => array("code" => 500, "error" => $exception->getMessage() . '<br/>' . $exception->getTraceAsString())
    ));
    return false;
  }
}

But when i have a problem in my services.php like error on connect to db or connect to redis, this doesn't work..

How can i use "dispacher->forward" in my services.php?

Obs: I tried de code bellow, but *dont *have success.

$di->setShared('db', function ($try = false) use ($config) {
    try {
      return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host"         => $config->database->host,
        "username"     => $config->database->username,
        "password"     => $config->database->password,
        "dbname"       => $config->database->dbname,
        'charset' => $config->database->charset,
        //"dialectClass" => '\Phalcon\Db\Dialect\MysqlExtended'
      ));
    } catch (Exception $e) {
      $dispatcher = new \Phalcon\Mvc\Dispatcher();
      $dispatcher->forward(array(
        'controller' => 'errors',
        'action' => 'show500',
        'params' => array(
          'code' => 500,
          'error' => $e->getMessage()
        )
      ));
    }
});

You basically wish for high level global error handler. You'd need to catch those exceptions at the root of runtime, i.e. your FrontPageController (index.php).

edited Mar '17

If you are accessing database not in dispatchloop then you are doing something wrong.

$di->setShared('db', function () use ($config) {
return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
        "host"         => $config->database->host,
        "username"     => $config->database->username,
        "password"     => $config->database->password,
        "dbname"       => $config->database->dbname,
        'charset' => $config->database->charset,
        //"dialectClass" => '\Phalcon\Db\Dialect\MysqlExtended'
      ));
});

Code like this will just work if you access db service in dispatch loop. If you access db outisde of it then obviously dispatcher beforeException won't work. As well as forward because there is nowhere to forward from.