5

I am implementing the following custom command for running a background processes:

namespace App\Console\Commands;

use App\Model\MyModel;
use Exception;
use Illuminate\Console\Command;

class MyCommand extends Command
{
    /**
     * @var string
     */
    protected $description = "Doing StuffyStuff";

    /**
     * @var string
     */
    protected $signature = "mycommand:dostuff";

    public function __construct()
    {
        parent::__construct();
    }

    public function handle(MyModel $model): void
    {
        //@todo Implement Upload
        try {
            $model->findOrFail(12);
            //Set Exit Status Code 0
        } catch (Exception $e) {
            //Set status code 1
        }
    }


}

So as you can see I want to specify the statuc code depending if an exception has been thrown or not. If success I want to use exit status code 0 and if fail I want to use exit status code 1 as Unix Spec specifies.

So do you have any Idea how to do that?

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
  • What do you excellently want to achieve ? – vrkansagara Aug 20 '19 at 08:45
  • What I want to achieve is when an exception is thrown to make the command exit a exit status code 1, as part of the exception handling. – Dimitrios Desyllas Aug 20 '19 at 08:47
  • Add $status into try and cache block with exist status code and catch into finally block and do whatever you want to do in finally block. – vrkansagara Aug 20 '19 at 08:48
  • My questions is How do you return into the console the desired exit status code. Usually In linux system a running command returns an exit status code. In my case it is the custom artisan command. – Dimitrios Desyllas Aug 20 '19 at 08:51
  • how about when it success "return 0;" otherwise, return 1; – Elad Aug 20 '19 at 08:51
  • 1
    @DimitriosDesyllas If you really want to make your code standard I would recommend to use php standard constant for output https://www.php.net/manual/en/reserved.constants.php – vrkansagara Aug 23 '19 at 14:52

1 Answers1

6

You can return the code wherever you want

public function handle(MyModel $model): int
    {
        //@todo Implement Upload
        try {
            $model->findOrFail(12);
            return 0;
        } catch (Exception $e) {
            $this->error($e->getMessage());
            return 1;
        }
    }

You can see an example & explain here

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
Elad
  • 891
  • 5
  • 15