简体   繁体   English

如何使用代码在 Laravel 控制台命令中中止/退出/停止/终止

[英]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.只需使用return语句而不是抛出异常。 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 .只需创建一个实现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:使用return和退出代码:

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

Return a 0 if all is ok, a non-zero positive value on errors:如果一切正常,则返回0 ,错误时返回非零正值:

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

1

This works with at least Laravel 6 onwards.这至少适用于 Laravel 6 以上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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