stardust4891
stardust4891

Reputation: 2550

how to Abort/exit/stop/terminate in laravel console command using code

Let's say I'm coding a command. How would I stop it completely in the middle of it running?

Example:

public function handle()
{
    if (!$this->good_times) {
        $this->error('Bad times');
        $this->exit();
    }

    // continue command stuff
}

I have tried:

throw new RuntimeException('Bad times');

But that dumps a bunch of ugliness in the terminal.

Upvotes: 12

Views: 23961

Answers (5)

bmatovu
bmatovu

Reputation: 4074

Just use a return statement instead of throwing an exception. Like...

public function handle()
{
    if (!$this->good_times) {
        $this->error('Bad times');
        // $this->exit();
        // throw new RuntimeException('Bad times');
        return self::FAILURE;
    }

    // ...
    return self::SUCCESS;
}

Upvotes: 19

Ramon
Ramon

Reputation: 99

You can use return or exit if you want to stop the command from within a function.

public function handle()
{
    return;
}
protected function stop() {
    exit;
}
    
public function handle()
{
    $this->stop();
}

Upvotes: -1

cweiske
cweiske

Reputation: 31117

Use return with the exit code number:

public function handle()
{
    $this->error('Invalid parameter: thiswillfail');
    return 1;
}

Return a 0 if all is ok, a non-zero positive value on errors:

$ ./artisan mycommand thiswillfail; echo $?
Invalid parameter: thiswillfail

1

This works with at least Laravel 6 onwards.

Upvotes: 0

Mateusz Będziński
Mateusz Będziński

Reputation: 157

private function foo()
{
    if (/* exception trigger condition */) {
        throw new \Exception('Exception message');
    }
    // ...
}

public function handle()
{
    try{
        $this->foo();
    } catch (\Exception $error){
        $this->error('An error occurred: ' . $error->getMessage());
    
        return;
    }
    
    $this->comment('All done');
}

Upvotes: 0

Yahya Uddin
Yahya Uddin

Reputation: 28901

Ran into this problem as well.

Just create an exception that implements ExceptionInterface.

use Exception;
use Symfony\Component\Console\Exception\ExceptionInterface;

class ConsoleException extends Exception implements ExceptionInterface
{

}

now when you throw the error:

throw new ConsoleException('Bad times');

You get the error without the stack trace.

Upvotes: 7

Related Questions