Filtre Symfony pour intercepter les exceptions

Problématique

Dans un projet symfony, il peut être intéressant de gérer soi-même certaines exceptions plutôt que de laisser Symfony les gérer seul.
Par exemple, au cours d’un développement, je devais réaliser une application consommant un webservice soap. Différentes méthodes du webservice étant appelées dans différentes actions d’un même module avec, en cas d’échec la levée d’une « WebserviceExeption ».

Avec une telle architecture, l’un des rares moyens que j’ai trouvé pour gérer toutes ces exceptions levées dans des actions et parfois même des modules différents, consiste à utiliser un filtre symfony.

Solution

lib/exceptionCatcherFilter.class.php :

class ExceptionCatcherFilter extends sfFilter
{
    public function execute($filterChain)
    {
       if (sfConfig::get('app_exceptionCatcherFilter')) {
           try {
               $filterChain->execute();
           } catch (sfStopException $e) {
               // This is an internally used symfony exception and shouldn't be blocked
               throw $e;
           } catch (Exception $e) {
                // Do something with the exception, other than just throwing it
           }
       } else {
           $filterChain->execute();
       }
    }
}

config/filters.yml :

rendering: ~
web_debug: ~
security:  ~
exceptionCatcherFilter:
  class: ExceptionCatcherFilter
cache:     ~
common:    ~
flash:     ~
execution: ~

Source: http://felix.phpbelgium.be/blog/2008/01/28/exception-catcher-filter-for-symfony/

Leave a comment

Your comment