Skip to content

Commit

Permalink
Render exceptions in developer console
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Jun 9, 2024
1 parent b1347cd commit 4df76c4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
16 changes: 12 additions & 4 deletions src/main/php/xp/web/dev/Console.class.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php namespace xp\web\dev;

use web\Filter;
use Throwable as Any;
use lang\Throwable;
use web\{Error, Filter};

/**
* The development console captures content written via `var_dump()`,
Expand Down Expand Up @@ -51,10 +53,13 @@ public function filter($req, $res, $invocation) {
yield from $invocation->proceed($req, $res->streaming(function($res, $length) use($capture) {
return $capture->length($length);
}));
} finally {
$capture->end($res);
$debug= ob_get_clean();
if (0 === strlen($debug)) return $capture->drain($res);
} catch (Any $e) {
$res->answer($e instanceof Error ? $e->status() : 500);
$debug= ob_get_clean()."\n".Throwable::wrap($e)->toString();
} finally {
$capture->end($res);
}

$console= sprintf(
Expand All @@ -67,7 +72,10 @@ public function filter($req, $res, $invocation) {
);
$target= $res->output()->stream(strlen($console));
try {
$target->begin(200, 'Debug', ['Content-Type' => ['text/html; charset=utf-8']]);
$target->begin(200, 'Debug', [
'Content-Type' => ['text/html; charset='.\xp::ENCODING],
'Cache-Control' => ['no-cache, no-store'],
]);
$target->write($console);
} finally {
$target->close();
Expand Down
35 changes: 34 additions & 1 deletion src/test/php/web/unittest/server/ConsoleTest.class.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php namespace web\unittest\server;

use lang\IllegalArgumentException;
use test\{Assert, Test, Values};
use web\io\{TestInput, TestOutput};
use web\{Filters, Request, Response};
use web\{Error, Filters, Request, Response};
use xp\web\dev\Console;

class ConsoleTest {
Expand Down Expand Up @@ -131,4 +132,36 @@ public function headers_appear_in_console() {
$res->output()->bytes()
);
}

#[Test]
public function uncaught_exceptions() {
$res= $this->handle(function($req, $res) {
throw new IllegalArgumentException('Test');
});

Assert::matches(
'/HTTP\/1.1 <span id="status">500 Internal Server Error<\/span>/',
$res->output()->bytes()
);
Assert::matches(
'/Exception lang.IllegalArgumentException \(Test\)/',
$res->output()->bytes()
);
}

#[Test]
public function uncaught_errors() {
$res= $this->handle(function($req, $res) {
throw new Error(404);
});

Assert::matches(
'/HTTP\/1.1 <span id="status">404 Not Found<\/span>/',
$res->output()->bytes()
);
Assert::matches(
'/Error web.Error\(#404: Not Found\)/',
$res->output()->bytes()
);
}
}

0 comments on commit 4df76c4

Please sign in to comment.