【问题标题】:how to Abort/exit/stop/terminate in laravel console command using code如何使用代码在 laravel 控制台命令中中止/退出/停止/终止
【发布时间】:2019-05-02 13:56:23
【问题描述】:

假设我正在编写一个命令。我如何在它运行的过程中完全停止它?

例子:

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

    // continue command stuff
}

我试过了:

throw new RuntimeException('Bad times');

但这会在终端中倾倒一堆丑陋的东西。

【问题讨论】:

    标签: php laravel laravel-5 command


    【解决方案1】:

    只需使用 return 语句,而不是抛出异常。喜欢...

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

    【讨论】:

    • 请注意,由于 Laravel 7 控制台命令不能返回 void,而只能返回整数。在示例中,return true 应更改为 return 0。但是,只返回一些东西(0 或 1)就可以了。
    【解决方案2】:

    也遇到了这个问题。

    只需创建一个实现ExceptionInterface 的异常。

    use Exception;
    use Symfony\Component\Console\Exception\ExceptionInterface;
    
    class ConsoleException extends Exception implements ExceptionInterface
    {
    
    }
    

    现在当你抛出错误时:

    throw new ConsoleException('Bad times');
    

    您会在没有堆栈跟踪的情况下得到错误。

    【讨论】:

      【解决方案3】:

      尝试这样使用

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

      【讨论】:

      • 我在 laravel 控制台命令中执行此操作,但在运行 phpunit 测试时会导致退出 phpunit 套件的问题。
      【解决方案4】:
      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');
      }
      

      【讨论】:

      • 不鼓励仅使用代码回答。请简要说明您的答案如何解决问题,以及为什么它可能优于已提供的其他答案。
      【解决方案5】:

      使用return 和退出代码:

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

      如果一切正常,返回一个0,一个非零的正值错误:

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

      这至少适用于 Laravel 6 及以上版本。

      【讨论】:

        猜你喜欢
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 2019-09-01
        相关资源
        最近更新 更多