Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ 11.x ] Adds ability to manually fail a command from outside the handle() method #51435

Merged

Conversation

ProjektGopher
Copy link
Contributor

@ProjektGopher ProjektGopher commented May 16, 2024

In a large and complex artisan command where smaller bits are extracted into separate methods (each of which is a possible failure point), we have a couple of options to exit with a non-zero exit code without dumping the entire Exception.

We can wrap the method call in a try/catch, and return in the catch block.

    public function handle()
    {
        try {
            $this->trigger_failure();
        } catch (ManuallyFailedException $e) {
            $this->error($e->getMessage());

            return static::FAILURE;
        }
    }

    protected function trigger_failure()
    {
        throw new ManuallyFailedException("whoops!");
    }

We can use a return value and wrap it in an if block.

    public function handle()
    {
        [$result, $error] = $this->trigger_failure();
        if (!is_null($error)) {
            $this->error($error->message);

            return static::FAILURE;
        }
    }

    protected function trigger_failure()
    {
        return [false, (object) [
            'message' => 'whoops!',
        ]];
    }

These obviously work just fine, but it's a paper cut I've run into many times. The Queue has a $this->fail() convenience method, so I've implemented one on the Command class to mimic it. This new approach feels more readable, and more intuitive. Since we're only working with a custom Exception, backwards compatibility is fully maintained. Here's an example of this new method of failing a command outside of the handle() method:

    public function handle()
    {
        $this->trigger_failure();
    }

    protected function trigger_failure()
    {
        $this->fail('Whoops!');
    }

@taylorotwell taylorotwell merged commit f8c0f59 into laravel:11.x May 16, 2024
28 checks passed
@ProjektGopher ProjektGopher deleted the feature/manually_fail_command branch May 16, 2024 22:28
@taylorotwell
Copy link
Member

@ProjektGopher feel like submitting a docs PR for this? 😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants