Skip to content

[HttpKernel] Add "handle-all-throwables option to handle thrown Error in addition to Exception` #47467

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
Oct 18, 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
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ CHANGELOG

* Add `resolve-env` option to `debug:config` command to display actual values of environment variables in dumped configuration
* Add `NotificationAssertionsTrait`
* Add option `framework.catch_all_throwables` to allow `Symfony\Component\HttpKernel\HttpKernel` to catch all kinds of `Throwable`
* Add option `framework.handle_all_throwables` to allow `Symfony\Component\HttpKernel\HttpKernel` to handle all kinds of `Throwable`
* Make `AbstractController::render()` able to deal with forms and deprecate `renderForm()`
* Deprecate the `Symfony\Component\Serializer\Normalizer\ObjectNormalizer` and
`Symfony\Component\Serializer\Normalizer\PropertyNormalizer` autowiring aliases, type-hint against
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +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()
->booleanNode('handle_all_throwables')->info('HttpKernel will handle all kinds of \Throwable')->end()
->end()
;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,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']);
$container->getDefinition('http_kernel')->replaceArgument(4, $config['handle_all_throwables'] ?? false);

// 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
56 changes: 0 additions & 56 deletions src/Symfony/Bundle/FrameworkBundle/Test/ExceptionSubscriber.php

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -657,7 +657,6 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'sanitizers' => [],
],
'exceptions' => [],
'catch_all_throwables' => false,
];
}
}
13 changes: 4 additions & 9 deletions src/Symfony/Bundle/FrameworkBundle/Tests/Functional/UidTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

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;
use Symfony\Component\Uid\UuidV4;
Expand All @@ -30,15 +28,12 @@ protected function setUp(): void
public function testArgumentValueResolverDisabled()
{
$client = $this->createClient(['test_case' => 'Uid', 'root_config' => 'config_disabled.yml']);
$client->catchExceptions(false);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need ExceptionSubscriber because we can do this instead.


$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->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');

$this->assertInstanceOf(\TypeError::class, $exception);
$this->assertStringContainsString(UidController::class.'::anyFormat(): Argument #1 ($userId) must be of type Symfony\Component\Uid\UuidV1, string given', $exception->getMessage());
$client->request('GET', '/1/uuid-v1/'.new UuidV1());
}

public function testArgumentValueResolverEnabled()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,3 @@ 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,7 +11,6 @@ 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,7 +86,6 @@ 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,7 +122,6 @@ 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 @@ -103,7 +103,6 @@ protected function configureContainer(ContainerConfigurator $c): void
$c->extension('framework', [
'http_method_override' => false,
'router' => ['utf8' => true],
'catch_all_throwables' => true,
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ 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,7 +11,6 @@ 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,7 +12,6 @@ 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": "^6.2",
"symfony/framework-bundle": "^5.4|^6.0",
"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": "<6.2",
"symfony/framework-bundle": "<5.4",
"symfony/ldap": "<5.4",
"symfony/twig-bundle": "<5.4"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
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 @@ -59,11 +58,6 @@ protected function configureContainer(ContainerBuilder $containerBuilder, Loader
'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', [
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ CHANGELOG
6.2
---

* Add constructor argument `bool $catchThrowable` to `HttpKernel`
* Add constructor argument `bool $handleAllThrowable` to `HttpKernel`
* Add `ControllerEvent::getAttributes()` to handle attributes on controllers
* Add `#[Cache]` to describe the default HTTP cache headers on controllers
* Add `absolute_uri` option to surrogate fragment renderers
Expand Down
15 changes: 5 additions & 10 deletions src/Symfony/Component/HttpKernel/HttpKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,15 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
protected $resolver;
protected $requestStack;
private ArgumentResolverInterface $argumentResolver;
private bool $catchThrowable;
private bool $handleAllThrowables;

public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null, bool $catchThrowable = false)
public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null, bool $handleAllThrowables = 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);
}
$this->handleAllThrowables = $handleAllThrowables;
}

public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
Expand All @@ -76,7 +73,7 @@ public function handle(Request $request, int $type = HttpKernelInterface::MAIN_R
try {
return $this->handleRaw($request, $type);
} catch (\Throwable $e) {
if (!$this->catchThrowable && !$e instanceof \Exception) {
if ($e instanceof \Error && !$this->handleAllThrowables) {
throw $e;
}

Expand Down Expand Up @@ -217,8 +214,6 @@ private function finishRequest(Request $request, int $type)

/**
* Handles a throwable by trying to convert it to a Response.
*
* @throws \Throwable
*/
private function handleThrowable(\Throwable $e, Request $request, int $type): Response
{
Expand Down Expand Up @@ -251,7 +246,7 @@ private function handleThrowable(\Throwable $e, Request $request, int $type): Re
try {
return $this->filterResponse($response, $request, $type);
} catch (\Throwable $e) {
if (!$this->catchThrowable && !$e instanceof \Exception) {
if ($e instanceof \Error && !$this->handleAllThrowables) {
throw $e;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,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), true);
$httpKernel = new HttpKernel(new EventDispatcher(), $resolver, null, $this->createMock(ArgumentResolverInterface::class));
$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, true);
return new HttpKernel($dispatcher, $controllerResolver, new RequestStack(), $argumentResolver);
}
}
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(), true);
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());

$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(), true);
$kernel = new HttpKernel($dispatcher, new ControllerResolver(), $requestStack, new ArgumentResolver());

$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, true);
$kernel = new HttpKernel(new EventDispatcher(), $controllerResolver, new RequestStack(), $argumentResolver);
$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($eventDispatcher ?? new EventDispatcher(), $this, null, $this, true);
parent::__construct($eventDispatcher ?? new EventDispatcher(), $this, null, $this);
}

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, true);
parent::__construct(new EventDispatcher(), $this, null, $this);
}

public function getBackendRequest()
Expand Down
12 changes: 5 additions & 7 deletions src/Symfony/Component/HttpKernel/Tests/HttpKernelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ public function testHandleWhenControllerThrowsAThrowableAndCatchIsTrueWithAHandl
$event->setResponse(new Response($event->getThrowable()->getMessage()));
});

$kernel = $this->getHttpKernel($dispatcher, function () { throw new \TypeError('foo'); });
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \TypeError('foo'); }, handleAllThrowables: true);
$response = $kernel->handle(new Request(), HttpKernelInterface::MAIN_REQUEST, true);

$this->assertEquals('500', $response->getStatusCode());
Expand All @@ -147,7 +147,7 @@ public function testHandleWhenControllerThrowsAThrowableAndCatchIsFalseWithAHand
$event->setResponse(new Response($event->getThrowable()->getMessage()));
});

$kernel = $this->getHttpKernel($dispatcher, function () { throw new \TypeError('foo'); });
$kernel = $this->getHttpKernel($dispatcher, function () { throw new \TypeError('foo'); }, handleAllThrowables: true);
$this->expectException(\TypeError::class);
$kernel->handle(new Request(), HttpKernelInterface::MAIN_REQUEST, false);
}
Expand All @@ -156,8 +156,6 @@ public function testHandleWhenControllerThrowsAThrowableAndCatchIsFalseWithAHand
* Catch exceptions: true
* Throwable type: TypeError
* Listener: true.
*
* @group legacy
*/
public function testHandleWhenControllerThrowsAThrowableAndCatchIsTrueNotHandlingThrowables()
{
Expand All @@ -178,7 +176,7 @@ public function testHandleWhenControllerThrowsAThrowableAndCatchIsTrueNotHandlin
->method('getArguments')
->willReturn([]);

$kernel = new HttpKernel($dispatcher, $controllerResolver, null, $argumentResolver, false);
$kernel = new HttpKernel($dispatcher, $controllerResolver, null, $argumentResolver);

$this->expectException(\TypeError::class);
$kernel->handle(new Request(), HttpKernelInterface::MAIN_REQUEST, true);
Expand Down Expand Up @@ -479,7 +477,7 @@ public function testInconsistentClientIpsOnMainRequests()
Request::setTrustedProxies([], -1);
}

private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = [])
private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $controller = null, RequestStack $requestStack = null, array $arguments = [], bool $handleAllThrowables = false)
{
if (null === $controller) {
$controller = function () { return new Response('Hello'); };
Expand All @@ -497,7 +495,7 @@ private function getHttpKernel(EventDispatcherInterface $eventDispatcher, $contr
->method('getArguments')
->willReturn($arguments);

return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver, true);
return new HttpKernel($eventDispatcher, $controllerResolver, $requestStack, $argumentResolver, $handleAllThrowables);
}

private function assertResponseEquals(Response $expected, Response $actual)
Expand Down
Loading