Skip to content

Commit

Permalink
Added thread error handler
Browse files Browse the repository at this point in the history
  • Loading branch information
dotfry committed Dec 13, 2019
1 parent c57c1d4 commit 0c4a921
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
10 changes: 5 additions & 5 deletions src/Pool/DTO/ThreadContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,20 @@ public function finished(): bool
/**
* Does execution finished with error.
*
* @return bool
* @return \Throwable|null
*/
public function hasError(): bool
public function getError(): ?\Throwable
{
if ($this->future->cancelled()) {
return false;
return null;
}

try {
$this->future->value();

return false;
return null;
} catch (\Throwable $e) {
return true;
return $e;
}
}

Expand Down
20 changes: 19 additions & 1 deletion src/Pool/Pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ class Pool implements PoolInterface
/** @var callable */
protected $closure;

/** @var callable */
protected $errorHandler;

/**
* Constructor.
*
Expand All @@ -38,6 +41,20 @@ public function __construct(string $autoloader, int $size, callable $threadFunct
}
}

/**
* Error handler.
*
* @param callable $callback
*
* @return Pool
*/
public function withErrorCallback(callable $callback): Pool
{
$this->errorHandler = $callback;

return $this;
}

/**
* @inheritdoc
*/
Expand Down Expand Up @@ -92,7 +109,8 @@ private function isFinished(array &$contexts): bool
foreach ($contexts as $idx => $context) {
if ($context->finished()) {
unset($contexts[$idx]);
if ($context->hasError()) {
$error = $context->getError();
if ($error && (!$this->errorHandler || ($this->errorHandler && ($this->errorHandler)($error)))) {
$this->run($context->getIndex(), $context->getArgs());

return false;
Expand Down

0 comments on commit 0c4a921

Please sign in to comment.