04/10/2014 - SYMFONY
To create a custom exception in symfony, you can just follow the simple steps below. Assuming that we want to throw our own exception when we catch any exceptions.
# sport/src/Football/FrontendBundle/Exception/CountryException.php
namespace Football\FrontendBundle\Exception;
use RuntimeException;
/**
* Triggered when Country entity related errors occur.
*/
class CountryException extends RuntimeException
{
}
namespace Football\FrontendBundle\Controller;
use Football\FrontendBundle\Exception\CountryException;
class CountryController extends Controller
{
public function createAction(Request $request)
{
// Some process here
try {
// Some process here
$em->persist($country);
$em->flush();
} catch (DBALException $e) {
$message = sprintf('DBALException [%i]: %s', $e->getCode(), $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException [%i]: %s', $e->getCode(), $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception [%i]: %s', $e->getCode(), $e->getMessage());
}
if (isset($message)) {
throw new CountryException($message);
}
return $this->redirect($this->generateUrl('country_create'));
}
}