Skip to content

Commit

Permalink
Allow overriding ErrorHandler, add exception listeners
Browse files Browse the repository at this point in the history
  • Loading branch information
mlocati committed Dec 13, 2024
1 parent 09798f7 commit 769c128
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
24 changes: 24 additions & 0 deletions concrete/src/Error/Handling/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ class ErrorHandler extends SymfonyErrorHandler
*/
protected $config;

/**
* @var callable[]
*/
protected $exceptionListeners = [];

public function __construct(LoggerInterface $logger, Repository $config)
{
$this->config = $config;
Expand Down Expand Up @@ -54,6 +59,19 @@ public function __construct(LoggerInterface $logger, Repository $config)
$this->throwAt($thrownErrors, true);
}

/**
* Add a callable to be invoked when we have an exception.
* If the callable returns true we won't do anything.
*
* @return $this
*/
public function addExceptionListener(callable $listener): self
{
$this->exceptionListeners[] = $listener;

return $this;
}

/**
* {@inheritDoc}
*
Expand All @@ -77,6 +95,12 @@ protected function getErrorEnhancers(): iterable
*/
protected function renderConcreteException(\Throwable $exception): void
{
foreach ($this->exceptionListeners as $exceptionListener) {
if ($exceptionListener($exception) === true) {
return;
}
}

$renderer = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? new CliErrorRenderer() : app(ConcreteErrorRenderer::class, ['config' => $this->config]);

$exception = $renderer->render($exception);
Expand Down
11 changes: 8 additions & 3 deletions concrete/src/Error/Provider/ErrorHandlingServiceProvider.php
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
<?php
namespace Concrete\Core\Error\Provider;

use Concrete\Core\Foundation\Service\Provider;
use Concrete\Core\Error\Handling\ErrorHandler;
use Concrete\Core\Foundation\Service\Provider;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerFactory;

class ErrorHandlingServiceProvider extends Provider
{
public function register()
{
$logger = $this->app->make(LoggerFactory::class)->createLogger(Channels::CHANNEL_EXCEPTIONS);
$handler = $this->app->make(ErrorHandler::class, ['logger' => $logger]);
if ($this->app->bound(ErrorHandler::class)) {
$handler = $this->app->make(ErrorHandler::class);
} else {
$logger = $this->app->make(LoggerFactory::class)->createLogger(Channels::CHANNEL_EXCEPTIONS);
$handler = $this->app->make(ErrorHandler::class, ['logger' => $logger]);
$this->app->instance(ErrorHandler::class, $handler);
}
$handler = ErrorHandler::register($handler);
$handler->setExceptionHandler([$handler, 'renderConcreteException']);
}
Expand Down

0 comments on commit 769c128

Please sign in to comment.