Tôi có một ứng dụng web đơn giản được tạo bởi một số gói Symfony3, tất cả các bộ điều khiển của chúng đều mở rộng BaseController. Tôi cũng có một AdminBundle. Để hiển thị một trang nhất định cho mỗi url không tồn tại, tôi bị hack (và thực hiện đơn giản) các ExceptionController.php gốc (từ TwigBundle):
<?php
namespace MyApp\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use MyApp\Controller\BaseController;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
class ExceptionController extends BaseController
{
/**
* Converts an Exception to a Response.
*
* @param Request $request The request
* @param FlattenException $exception A FlattenException instance
* @param DebugLoggerInterface $logger A DebugLoggerInterface instance
*
* @return Response
* @throws \InvalidArgumentException When the exception template does not exist
*/
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
$currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1));
$code = $exception->getStatusCode();
return $this->render('MyappAdminBundle:Admin:error.html.twig',
array(
'status_code' => $code,
'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
'exception' => $exception,
'logger' => $logger,
'currentContent' => $currentContent,
)
);
}
/**
* @param int $startObLevel
*
* @return string
*/
protected function getAndCleanOutputBuffering($startObLevel)
{
if (ob_get_level() <= $startObLevel) {
return '';
}
Response::closeOutputBuffers($startObLevel + 1, true);
return ob_get_clean();
}
}
tôi xác định mẫu lỗi của tôi như tôi thích.
tôi cần phải thêm dòng sau trong config.yml
twig:
exception_controller: MyappAdminBundle:Exception:show
ps Tôi chắc chắn mã của tôi có thể được cải thiện, nhưng nó hoạt động tốt.
Cảm ơn, người nghe sự kiện là con đường để tôi nghĩ, nhưng $ this-> templating không hợp lệ. Tôi cũng đã thử $ event-> templating. Tôi không nghĩ rằng phương pháp điều khiển thông thường có sẵn. Tôi nhận được một thuộc tính Undefined: Symfony \ Component \ HttpKernel \ Event \ GetResponseForExceptionEvent :: $ templating in ... – user2143356
Bạn đúng, các phương thức điều khiển thông thường không có sẵn vì đó là các bí danh cho các cuộc gọi phương thức trên các dịch vụ. Bạn nên tiêm dịch vụ 'templating' vào trình lắng nghe sự kiện trong phần mô tả dịch vụ. –
Tôi đã không hiện thực tại thời điểm này chỉ cần thiết lập một mẫu Twig, không phải là một trang hoặc bộ điều khiển thực sự. – user2143356