Added Hyperf\Command\Listener\FailToHandleListener. (#4723)

This commit is contained in:
李铭昕 2022-05-01 19:04:27 +08:00 committed by GitHub
parent 4dcd47d42d
commit 3a5b5382c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 3 deletions

View File

@ -429,6 +429,8 @@ abstract class Command extends SymfonyCommand
throw $exception;
}
$this->output && $this->error($exception->getMessage());
$this->eventDispatcher->dispatch(new Event\FailToHandle($this, $exception));
return $this->exitCode = $exception->getCode();
} finally {

View File

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Command\Listener;
use Hyperf\Command\Event\FailToHandle;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerInterface;
class FailToHandleListener implements ListenerInterface
{
public function __construct(private ContainerInterface $container)
{
}
public function listen(): array
{
return [
FailToHandle::class,
];
}
/**
* @param FailToHandle $event
*/
public function process(object $event): void
{
if ($this->container->has(StdoutLoggerInterface::class) && $logger = $this->container->get(StdoutLoggerInterface::class)) {
$logger->error((string) $event->getThrowable());
}
}
}

View File

@ -57,17 +57,20 @@ class CommandTest extends TestCase
$command = new ClassInvoker(new FooExceptionCommand('foo'));
$input = Mockery::mock(InputInterface::class);
$input->shouldReceive('getOption')->andReturnFalse();
$exitCode = $command->execute($input, Mockery::mock(OutputInterface::class));
$output = Mockery::mock(OutputInterface::class);
$output->shouldReceive('writeln')->withAnyArgs()->andReturnNull();
$exitCode = $command->execute($input, $output);
$this->assertSame(99, $exitCode);
/** @var FooExitCommand $command */
$command = new ClassInvoker(new FooExitCommand());
$exitCode = $command->execute($input, Mockery::mock(OutputInterface::class));
$exitCode = $command->execute($input, $output);
$this->assertSame(11, $exitCode);
/** @var FooCommand $command */
$command = new ClassInvoker(new FooCommand());
$exitCode = $command->execute($input, Mockery::mock(OutputInterface::class));
$exitCode = $command->execute($input, $output);
$this->assertSame(0, $exitCode);
}