mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-11 09:56:32 +00:00
bug #3830 Catch errors thrown during template rendering (richards-square)
This PR was squashed before being merged into the 3.x branch.
Discussion
----------
Catch errors thrown during template rendering
Some errors, like not providing a function the proper number of arguments or division by zero, extend from `\Error` rather than `\Exception`. This PR catches these types of errors during template rendering and throws a `RuntimeError` in order to provide better debugging information.
Commits
-------
85bf01b4 Catch errors thrown during template rendering
This commit is contained in:
+1
-1
@@ -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
@@ -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();
|
||||
|
||||
|
||||
@@ -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 [
|
||||
|
||||
Reference in New Issue
Block a user