Skip to content

Commit 9d34da7

Browse files
authored
Merge pull request #18 from hypervel/feature/support-manual-failed-exception
Feat: Support `fail` function in command
2 parents a6a4166 + 8324a88 commit 9d34da7

File tree

3 files changed

+43
-4
lines changed

3 files changed

+43
-4
lines changed

src/console/src/ClosureCommand.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,16 @@ public function handle(): int
4747
}
4848
}
4949

50-
return (int) $this->container->call(
51-
$this->callback->bindTo($this, $this),
52-
$parameters
53-
);
50+
try {
51+
return (int) $this->container->call(
52+
$this->callback->bindTo($this, $this),
53+
$parameters
54+
);
55+
} catch (ManuallyFailedException $e) {
56+
$this->components->error($e->getMessage());
57+
58+
return static::FAILURE;
59+
}
5460
}
5561

5662
/**

src/console/src/Command.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int
4141
$this->exitCode = $statusCode;
4242
}
4343
$this->eventDispatcher?->dispatch(new AfterHandle($this));
44+
} catch (ManuallyFailedException $e) {
45+
$this->components->error($e->getMessage());
46+
47+
return $this->exitCode = static::FAILURE;
4448
} catch (Throwable $exception) {
4549
if (class_exists(ExitException::class) && $exception instanceof ExitException) {
4650
return $this->exitCode = (int) $exception->getStatus();
@@ -79,4 +83,22 @@ protected function replaceOutput(): void
7983
$this->output = $this->app->get(OutputInterface::class);
8084
}
8185
}
86+
87+
/**
88+
* Fail the command manually.
89+
*
90+
* @throws ManuallyFailedException|Throwable
91+
*/
92+
public function fail(null|string|Throwable $exception = null): void
93+
{
94+
if (is_null($exception)) {
95+
$exception = 'Command failed manually.';
96+
}
97+
98+
if (is_string($exception)) {
99+
$exception = new ManuallyFailedException($exception);
100+
}
101+
102+
throw $exception;
103+
}
82104
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Hypervel\Console;
6+
7+
use RuntimeException;
8+
9+
class ManuallyFailedException extends RuntimeException
10+
{
11+
}

0 commit comments

Comments
 (0)