Symfony2 custom exceptions

When using the Symfony2 Framework it is often better to create custom exceptions to handle unique circumstances rather than incorrectly utilising one of the many pre-existing Symfony exception types. Using an interface improves code cohesion, allows the adding of custom functionality as needed and is super easy to setup.

The first step is to create a custom exception interface.

namespace AppBundle\Exception;

interface AppBundleExceptionInterface
{
}

Then create a custom exception class (perhaps in an Exception directory if it suits your project’s structure):

namespace AppBundle\Exception;

class NewTypeOfException extends \Exception implements AppBundleExceptionInterface
{
}

This exception can now be thrown and caught as desired, just be sure to name your exceptions well. You may be throwing them long after they were originally created!

Advertisements

Leave a Reply