A personnal repository of everything that took me way too long to figure out...
dimanche 9 octobre 2011
Generate specific error pages with Symfony2
404 and 500 errors
Symfony2 allows to customize error pages by overriding Twig templates as decribed here. You can override the Twig templates for a range of typical cases like :
error.html.twig
exception.html.twig
error404.html.twig
and various other formats
From the controller, you can render a 500 error template by calling :
throw new \Exception('There is something wrong');
Or for a 404 error :
throw $this->createNotFoundException('The product does not exist');
More customized errors
But if you want to render, let's say a 402 exception, you have to use :
// At the beginnig of the file
use Symfony\Component\HttpKernel\Exception\HttpExcetion;
// In the controller
throw new HttpException(402,'There is something wrong');
If you want to display this custom message in the template, you have to add :
// Code of the error
{{ status_code }}
// Standard name of the error
{{ status_text }}
// Text you specified when throwing the exception
{{ exception.message|e|replace({"n": '<br/ >'})|format_file_from_text }}
Aucun commentaire:
Enregistrer un commentaire