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:

all:
.global:
  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 {
               $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();
       }
    }
}

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:  ~
exceptionCatcherFilter:
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.

3 Responses to “Exception catcher filter for Symfony”


  • Ey, thanks for the Idea, it will be so usefull in my proyect.
    JAP

  • 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.

  • 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 ?

    thanks

Leave a Reply