I am using Symfony2 for my web project, and I have several controllers that have exactly the same try catch block
<?php
class MyBaseController extends Controller {
private $manager = new MyManager();
// Some generic stuff
}
class MyController1 extends MyBaseController {
try {
$manager->one();
}
catch (Exception $e) {
return $this->someOtherMessage();
}
}
class MyController2 extends MyBaseController {
try {
$manager->two();
}
catch (Exception $e) {
return $this->someOtherMessage();
}
}
class MyController3 extends MyBaseController {
try {
$manager->three();
}
catch (Exception $e) {
return $this->someOtherMessage();
}
}
How could I write this to avoid so much duplication?
If every controller may send a specific exception, you shouldn't need a try/catch block for each method in your controller.
I see two ways to handle this.
First, if this is a global exception which can be thrown, and you just want to render another message than the default 500 error message. You can override the default template given, by creating your own error500.html.twig
in your app/Resources
folder
Another way to handle it is to create a custom exception tied with an event listener.
I would create my own exception like ManagerException
which will be handled by the event listener.
class ManagerException extends Exception {}
Your manager(s) would now throw this exception instead.
Note: You can create any exception you want as long as it extends this base exception
class RuntimeManagerException extends ManagerException {}
Then you can declare your event listener
services.yml
services:
manager_exception.listener:
class: Acme\FooBundle\Listener\ManagerExceptionListener
arguments: [ @templating ]
tags:
-
name: kernel.event_listener
event: kernel.exception
method: onKernelException
Acme\FooBundle\Listener\ManagerExceptionListener
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
class ManagerExceptionListener
{
protected $twig;
public function __construct(EngineInterface $twig)
{
$this->twig = $twig;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if (!($exception instanceof ManagerException)) {
return;
}
$response = new Response;
$response->setContent($this->twig->render('errorpage.html.twig'));
$event->setResponse($response);
}
}