我使用symfony 2.8版本与php模板。我可以使用php模板创建一个自定义的错误页面吗?
当然。
在services.yml
中,为异常添加侦听器:
listener.exception:
class: Symfony'Component'HttpKernel'EventListener'ExceptionListener
arguments: ["MyWebsite''Controller''ExceptionController::exceptionAction"]
tags:
- {name: 'kernel.event_subscriber'}
那么你的控制器就是一个普通的控制器:
<?php
namespace MyWebsite'Controller;
use Symfony'Component'Debug'Exception'FlattenException;
use Symfony'Component'HttpFoundation'Response;
class ExceptionController extends AbstractController
{
public function exceptionAction(FlattenException $exception)
{
$text = $exception->getMessage() ;
if (isset(Response::$statusTexts[$exception->getStatusCode()])) {
$text = Response::$statusTexts[$exception->getStatusCode()];
}
$response = new Response(null);
$response->setStatusCode($exception->getStatusCode());
return $this->render(
'exception.html.twig', // Here your template
['error' =>$text],
$response
);
}
}