Catch errors thrown during template rendering

This commit is contained in:
Drew Richards
2023-04-07 13:39:09 -04:00
committed by Fabien Potencier
parent 78c18ad58e
commit 85bf01b4ab
3 changed files with 25 additions and 3 deletions
+1 -1
View File
@@ -53,7 +53,7 @@ class Error extends \Exception
* @param int $lineno The template line where the error occurred
* @param Source|null $source The source context where the error occurred
*/
public function __construct(string $message, int $lineno = -1, Source $source = null, \Exception $previous = null)
public function __construct(string $message, int $lineno = -1, Source $source = null, \Throwable $previous = null)
{
parent::__construct('', 0, $previous);
+2 -2
View File
@@ -181,7 +181,7 @@ abstract class Template
}
throw $e;
} catch (\Exception $e) {
} catch (\Throwable $e) {
$e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e);
$e->guess();
@@ -404,7 +404,7 @@ abstract class Template
}
throw $e;
} catch (\Exception $e) {
} catch (\Throwable $e) {
$e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e);
$e->guess();
+22
View File
@@ -234,6 +234,28 @@ EOHTML
}
}
public function testTwigArgumentCountErrorThrowsRuntimeExceptions()
{
$loader = new ArrayLoader([
'argument-error.html' => <<<EOHTML
{# max requires at least one argument #}
{{ max() }}
EOHTML
]);
$twig = new Environment($loader, ['debug' => true, 'cache' => false]);
$template = $twig->load('argument-error.html');
try {
$template->render();
$this->fail();
} catch (RuntimeError $e) {
$this->assertEquals(2, $e->getTemplateLine());
$this->assertEquals('argument-error.html', $e->getSourceContext()->getName());
}
}
public function getErroredTemplates()
{
return [