Exception catcher filter for Symfony

Update: Updated the class to have a cleaner code syntax.

Recently, I needed a different way of processing my own defined exceptions in symfony. The cleanest solution was to implement a symfony filter, as I didn’t feel like try-catching every action available in my application :)

First thing to do is let symfony know when we can enable the filter.
Edit apps//config/app.yml and add the following:

  exceptionCatcherFilter: on

Next up is writing the actual filter.
Create apps//lib/exceptionCatcherFilter.class.php:

class ExceptionCatcherFilter extends sfFilter
    public function execute($filterChain)
       if (sfConfig::get('app_exceptionCatcherFilter')) {
           try {
           } 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 {

Basically, this checks if we have enabled our custom filter, then tries to execute it. If it does throw an exception, the exception gets catched. When the exception is not of class ‘sfStopException’, we can do something with it (for example, log it to a database or send mails or whatever). If we don’t have the filter enabled, the chain should still move on and pass execution to the next filter in the chain.

Last step that needs to be done is placing our filter somewhere in the chain of filters that is active in our application.
Edit apps//config/filters.yml:

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

This is, of course, a very simple version of such a filter but it does the job and can easily be extended to do whatever you need.
The current context is retrieved by: $this->getContext();, so you should have a look at that too.

5 responses to “Exception catcher filter for Symfony”

  1. Filtre Symfony pour intercepter les exceptions…

    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 …

  2. Thanks for this. This made it very easy for me to log all exceptions to a specific DB table. And as a side note, I’m not sure what version of Symfony you’re using, but this basic concept works effectively under Symfony 1.4 for me.

  3. hi,
    i hope you read your old post …

    i have a problem with sfError404Exception, your filter can’t intercept them ….
    do you have any idea ?