Skip to content

[FrameworkBundle][HttpKernel] Add deprecation warning to show HttpKernel::handle() will catch throwables #45997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* Deprecate the `Symfony\Component\Serializer\Normalizer\ObjectNormalizer` and
`Symfony\Component\Serializer\Normalizer\PropertyNormalizer` autowiring aliases, type-hint against
`Symfony\Component\Serializer\Normalizer\NormalizerInterface` or implement `NormalizerAwareInterface` instead
* Add option `framework.catch_all_throwables` to allow `Symfony\Component\HttpKernel\HttpKernel` to catch all kinds of `Throwable`

6.1
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->scalarNode('error_controller')
->defaultValue('error_controller')
->end()
->booleanNode('catch_all_throwables')->defaultFalse()->info('HttpKernel will catch all kinds of \Throwable')->end()
->end()
;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ public function load(array $configs, ContainerBuilder $container)

$container->getDefinition('locale_listener')->replaceArgument(3, $config['set_locale_from_accept_language']);
$container->getDefinition('response_listener')->replaceArgument(1, $config['set_content_language_from_locale']);
$container->getDefinition('http_kernel')->replaceArgument(4, $config['catch_all_throwables']);

// If the slugger is used but the String component is not available, we should throw an error
if (!ContainerBuilder::willBeAvailable('symfony/string', SluggerInterface::class, ['symfony/framework-bundle'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ class_exists(WorkflowEvents::class) ? WorkflowEvents::ALIASES : []
service('controller_resolver'),
service('request_stack'),
service('argument_resolver'),
false,
])
->tag('container.hot_path')
->tag('container.preload', ['class' => HttpKernelRunner::class])
Expand Down
56 changes: 56 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/Test/ExceptionSubscriber.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\FrameworkBundle\Test;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;

/**
* This event subscriber allows you to inspect all exceptions thrown by the application.
* This is useful since the HttpKernel catches all throwables and turns them into
* an HTTP response.
*
* This class should only be used in tests.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ExceptionSubscriber implements EventSubscriberInterface
{
/**
* @var list<\Throwable>
*/
private static array $exceptions = [];

public function onKernelException(ExceptionEvent $event)
{
self::$exceptions[] = $event->getThrowable();
}

/**
* @return list<\Throwable>
*/
public static function shiftAll(): array
{
$exceptions = self::$exceptions;
self::$exceptions = [];

return $exceptions;
}

public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,7 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'sanitizers' => [],
],
'exceptions' => [],
'catch_all_throwables' => false,
];
}
}
11 changes: 8 additions & 3 deletions src/Symfony/Bundle/FrameworkBundle/Tests/Functional/UidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\Test\ExceptionSubscriber;
use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\UidController;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\UuidV1;
Expand All @@ -31,12 +32,16 @@ protected function setUp(): void

public function testArgumentValueResolverDisabled()
{
$this->expectException(\TypeError::class);
$this->expectExceptionMessage('Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\UidController::anyFormat(): Argument #1 ($userId) must be of type Symfony\Component\Uid\UuidV1, string given');

$client = $this->createClient(['test_case' => 'Uid', 'root_config' => 'config_disabled.yml']);

$client->request('GET', '/1/uuid-v1/'.new UuidV1());
$this->assertSame(500, $client->getResponse()->getStatusCode());
$exceptions = ExceptionSubscriber::shiftAll();
$this->assertCount(1, $exceptions);
$exception = reset($exceptions);

$this->assertInstanceOf(\TypeError::class, $exception);
$this->assertStringContainsString('Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller\UidController::anyFormat(): Argument #1 ($userId) must be of type Symfony\Component\Uid\UuidV1, string given', $exception->getMessage());
}

public function testArgumentValueResolverEnabled()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,8 @@ framework:
http_method_override: false
uid:
enabled: false

services:
Symfony\Bundle\FrameworkBundle\Test\ExceptionSubscriber:
tags:
- { name: kernel.event_subscriber }
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ framework:
enabled_locales: ['en', 'fr']
session:
storage_factory_id: session.storage.factory.mock_file
catch_all_throwables: true

services:
logger: { class: Psr\Log\NullLogger }
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ protected function configureContainer(ContainerBuilder $c, LoaderInterface $load
'http_method_override' => false,
'secret' => '$ecret',
'router' => ['utf8' => true],
'catch_all_throwables' => true,
]);

$c->setParameter('halloween', 'Have a great day!');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ protected function configureContainer(ContainerConfigurator $c): void
$c->extension('framework', [
'http_method_override' => false,
'router' => ['utf8' => true],
'catch_all_throwables' => true,
]);
$c->services()->set('logger', NullLogger::class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ protected function configureContainer(ContainerConfigurator $c): void
->factory([$this, 'createHalloween'])
->arg('$halloween', '%halloween%');

$c->extension('framework', ['http_method_override' => false, 'router' => ['utf8' => true]]);
$c->extension('framework', [
'http_method_override' => false,
'router' => ['utf8' => true],
'catch_all_throwables' => true,
]);
}
}
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"symfony/error-handler": "^6.1",
"symfony/event-dispatcher": "^5.4|^6.0",
"symfony/http-foundation": "^5.4|^6.0",
"symfony/http-kernel": "^6.1",
"symfony/http-kernel": "^6.2",
"symfony/polyfill-mbstring": "~1.0",
"symfony/filesystem": "^5.4|^6.0",
"symfony/finder": "^5.4|^6.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ framework:
profiler: false
session:
storage_factory_id: session.storage.factory.mock_file
catch_all_throwables: true

services:
logger: { class: Psr\Log\NullLogger }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ framework:
session:
storage_factory_id: session.storage.factory.mock_file
profiler: { only_exceptions: false }
catch_all_throwables: true

services:
logger: { class: Psr\Log\NullLogger }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ framework:
session:
storage_factory_id: session.storage.factory.mock_file
profiler: { only_exceptions: false }
catch_all_throwables: true

services:
logger: { class: Psr\Log\NullLogger }
4 changes: 2 additions & 2 deletions src/Symfony/Bundle/SecurityBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"symfony/dom-crawler": "^5.4|^6.0",
"symfony/expression-language": "^5.4|^6.0",
"symfony/form": "^5.4|^6.0",
"symfony/framework-bundle": "^5.4|^6.0",
"symfony/framework-bundle": "^6.2",
"symfony/ldap": "^5.4|^6.0",
"symfony/process": "^5.4|^6.0",
"symfony/rate-limiter": "^5.4|^6.0",
Expand All @@ -53,7 +53,7 @@
"conflict": {
"symfony/browser-kit": "<5.4",
"symfony/console": "<5.4",
"symfony/framework-bundle": "<5.4",
"symfony/framework-bundle": "<6.2",
"symfony/ldap": "<5.4",
"symfony/twig-bundle": "<5.4"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Psr\Log\NullLogger;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Bundle\FrameworkBundle\Test\ExceptionSubscriber;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
Expand Down Expand Up @@ -50,13 +51,20 @@ protected function configureRoutes(RoutingConfigurator $routes): void

protected function configureContainer(ContainerBuilder $containerBuilder, LoaderInterface $loader): void
{
$containerBuilder->loadFromExtension('framework', [
$config = [
'http_method_override' => false,
'secret' => 'foo-secret',
'profiler' => ['only_exceptions' => false],
'session' => ['storage_factory_id' => 'session.storage.factory.mock_file'],
'router' => ['utf8' => true],
]);
];

// If Symfony >= 6.2
if (class_exists(ExceptionSubscriber::class)) {
$config['catch_all_throwables'] = true;
}

$containerBuilder->loadFromExtension('framework', $config);

$containerBuilder->loadFromExtension('web_profiler', [
'toolbar' => true,
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

6.2
---

* Add constructor argument `bool $catchThrowable` to `HttpKernel`

6.1
---

Expand Down
21 changes: 17 additions & 4 deletions src/Symfony/Component/HttpKernel/HttpKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,18 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
protected $resolver;
protected $requestStack;
private ArgumentResolverInterface $argumentResolver;
private bool $catchThrowable;

public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null)
public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null, bool $catchThrowable = false)
{
$this->dispatcher = $dispatcher;
$this->resolver = $resolver;
$this->requestStack = $requestStack ?? new RequestStack();
$this->argumentResolver = $argumentResolver ?? new ArgumentResolver();
$this->catchThrowable = $catchThrowable;
if (!$catchThrowable) {
trigger_deprecation('symfony/http-kernel', '6.2', 'Starting from 7.0, "%s::handle()" will catch \Throwable exceptions and convert them to HttpFoundation responses. Pass $catchThrowable=true to adapt to this behavior now.', self::class);
}
}

/**
Expand All @@ -72,7 +77,11 @@ public function handle(Request $request, int $type = HttpKernelInterface::MAIN_R

try {
return $this->handleRaw($request, $type);
} catch (\Exception $e) {
} catch (\Throwable $e) {
if (!$this->catchThrowable && !$e instanceof \Exception) {
throw $e;
}

if ($e instanceof RequestExceptionInterface) {
$e = new BadRequestHttpException($e->getMessage(), $e);
}
Expand Down Expand Up @@ -205,7 +214,7 @@ private function finishRequest(Request $request, int $type)
/**
* Handles a throwable by trying to convert it to a Response.
*
* @throws \Exception
* @throws \Throwable
*/
private function handleThrowable(\Throwable $e, Request $request, int $type): Response
{
Expand Down Expand Up @@ -237,7 +246,11 @@ private function handleThrowable(\Throwable $e, Request $request, int $type): Re

try {
return $this->filterResponse($response, $request, $type);
} catch (\Exception) {
} catch (\Throwable $e) {
if (!$this->catchThrowable && !$e instanceof \Exception) {
throw $e;
}

return $response;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ protected function createResponse()
protected function injectController($collector, $controller, $request)
{
$resolver = $this->createMock(ControllerResolverInterface::class);
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->createMock(ArgumentResolverInterface::class));
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->createMock(ArgumentResolverInterface::class), true);
$event = new ControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MAIN_REQUEST);
$collector->onKernelController($event);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,6 @@ protected function getHttpKernel($dispatcher)
$argumentResolver = $this->createMock(ArgumentResolverInterface::class);
$argumentResolver->expects($this->once())->method('getArguments')->willReturn([]);

return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver, true);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ public function testWithBadRequest()
return new Response('Exception handled', 400);
}));

$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver(), true);

$request = Request::create('http://localhost/');
$request->headers->set('host', '###');
Expand All @@ -195,7 +195,7 @@ public function testNoRoutingConfigurationResponse()
$dispatcher = new EventDispatcher();
$dispatcher->addSubscriber(new RouterListener($requestMatcher, $requestStack, new RequestContext()));

$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver(), true);

$request = Request::create('http://localhost/');
$response = $kernel->handle($request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public function testExceptionInSubRequestsDoesNotMangleOutputBuffers()
->willReturn([])
;

$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver);
$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver, true);
$renderer = new InlineFragmentRenderer($kernel);

// simulate a main request with output buffering
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public function __construct($body, $status, $headers, \Closure $customizer = nul
$this->headers = $headers;
$this->customizer = $customizer;

parent::__construct(new EventDispatcher(), $this, null, $this);
parent::__construct(new EventDispatcher(), $this, null, $this, true);
}

public function assert(\Closure $callback)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function __construct($responses)
$this->headers[] = $response['headers'];
}

parent::__construct(new EventDispatcher(), $this, null, $this);
parent::__construct(new EventDispatcher(), $this, null, $this, true);
}

public function getBackendRequest()
Expand Down
Loading