Skip to content

Commit 7f72f23

Browse files
author
Jérémy VIGNELLES
committed
Handle exceptions and throwables in templates
1 parent 4e54c44 commit 7f72f23

3 files changed

Lines changed: 47 additions & 4 deletions

File tree

src/PhpRenderer.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public function render(ResponseInterface $response, $template, array $data = [])
6262
$output = $this->fetch($template, $data);
6363

6464
$response->getBody()->write($output);
65-
65+
6666
return $response;
6767
}
6868

@@ -164,9 +164,17 @@ public function fetch($template, array $data = []) {
164164
*/
165165
$data = array_merge($this->attributes, $data);
166166

167-
ob_start();
168-
$this->protectedIncludeScope($this->templatePath . $template, $data);
169-
$output = ob_get_clean();
167+
try {
168+
ob_start();
169+
$this->protectedIncludeScope($this->templatePath . $template, $data);
170+
$output = ob_get_clean();
171+
} catch(\Throwable $e) { // PHP 7+
172+
ob_end_clean();
173+
throw $e;
174+
} catch(\Exception $e) { // PHP < 7
175+
ob_end_clean();
176+
throw $e;
177+
}
170178

171179
return $output;
172180
}

tests/PhpRendererTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,32 @@ public function testAttributeMerging() {
4343
$this->assertEquals("Hi", $newResponse->getBody()->getContents());
4444
}
4545

46+
public function testExceptionInTemplate() {
47+
$renderer = new \Slim\Views\PhpRenderer("tests/");
48+
49+
$headers = new Headers();
50+
$body = new Body(fopen('php://temp', 'r+'));
51+
$response = new Response(200, $headers, $body);
52+
53+
try {
54+
$newResponse = $renderer->render($response, "testException.php");
55+
} catch (Throwable $t) { // PHP 7+
56+
// Simulates an error template
57+
$newResponse = $renderer->render($response, "testTemplate.php", [
58+
"hello" => "Hi"
59+
]);
60+
} catch (Exception $e) { // PHP < 7
61+
// Simulates an error template
62+
$newResponse = $renderer->render($response, "testTemplate.php", [
63+
"hello" => "Hi"
64+
]);
65+
}
66+
67+
$newResponse->getBody()->rewind();
68+
69+
$this->assertEquals("Hi", $newResponse->getBody()->getContents());
70+
}
71+
4672
/**
4773
* @expectedException InvalidArgumentException
4874
*/

tests/testException.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Hello world. You should not see this because there is an error in the template.
2+
<?php
3+
$exception = new Exception('An error occurred');
4+
if($exception instanceof Throwable) {
5+
echo 2/0;
6+
}
7+
8+
throw $exception;
9+
?>

0 commit comments

Comments
 (0)