简体   繁体   中英

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.

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;
    }

    // ...
}

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.

try to used like that

public function handle()
    {
        try {
            if(!isset($x)){
                throw new \Exception('not found');
            }
        }catch(\Exception $e){
            exit($e->getMessage());
        }

        $this->info("test here");
    }
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');
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM