Symfony2 - Best Practices to trigger 404 exception Symfony2 - Best Practices to trigger 404 exception symfony symfony

Symfony2 - Best Practices to trigger 404 exception


You have to put your exceptions in methods that are called by your controller, and use those methods in every controller so you don't have to duplicate the code.

You can :

The first case provides a cleaner code but add a little more complexity, the second case is faster to implement.


my common practice is your code a some bit shorter

    public function getProductBySlug($slug)    {        $product = $this->findOneBySlug($slug);        if (!$product) {            return $this->createNotFoundException("This does not exist");        }        return $product ;    }

http://api.symfony.com/2.0/Symfony/Bundle/FrameworkBundle/Controller/Controller.html


Throw an HttpException in a service/repository is a bad idea. If you need this service in a command or must outsource them in a other example, you have bad cards.

The best solution is throw a (custom) exception in your services and repositories or sometimes return null or a null object. Then the controller can throw an HttpException which triggers an 404 page or forward to an another page.

Convert a NotFoundException to a 404 page is the default behaviour, but this can be changed.

Clean code should always be your goal, then you have less problems if your code grown up or your requirements has been changed. Write 2 lines of code more takes 2s, but maintain bad code can take hours.