Skip to content

Commit

Permalink
Refactored handling of exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
Gesparo committed Aug 28, 2023
1 parent 05b6d7c commit 596ec31
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
9 changes: 0 additions & 9 deletions application/console/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,5 @@
try {
(new App())->run($argv);
} catch (Throwable $exception) {

Check failure on line 11 in application/console/app.php

View workflow job for this annotation

GitHub Actions / phpcs

Blank line found at start of control structure
$trace = json_encode($exception->getTrace(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$message = <<<EOL
Exception: '{$exception->getMessage()}'
Code: '{$exception->getCode()}'
Trace:
$trace
EOL;

fwrite(STDERR, $message . PHP_EOL);
}
2 changes: 2 additions & 0 deletions application/src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public function run(array $arguments): void

try {
(new MainController($request, $config))->index();
} catch (\Throwable $exception) {
(new ExceptionHandler())->handle($exception);
} finally {
// additional protection when __destruct will not call in BaseSocket class
if (
Expand Down
29 changes: 29 additions & 0 deletions application/src/ExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace Gesparo\Hw;

class ExceptionHandler
{
public function handle(\Throwable $exception): void
{
fwrite(STDERR, $this->prepareMessage($exception) . PHP_EOL);
}

/**
* @throws \JsonException
*/
private function prepareMessage(\Throwable $exception): string
{
$trace = json_encode($exception->getTrace(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);

return <<<EOL
Exception: '{$exception->getMessage()}'
Code: '{$exception->getCode()}'
Trace:
$trace
EOL;
}
}

0 comments on commit 596ec31

Please sign in to comment.