How to accurately handle exceptions in Artisan commands

Using Lumen to create an API is a love of Laravel, but all the views that come with it were superfluous for the project I'm creating.

In any case, I made a series of commands that go out and collect data and store them in a database.

<?php 

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

use App\User;

class GetItems extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'GetItems';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Get items and store it into the Database";

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->info("Collecting ...");

       $users = User::all();

       foreach( $users as $user)
       {
           $user->getItems();
       }

   }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [];
    }

}

I have 3 identical commands, each of which collects slightly different data sets.

Is there a way that I can insert a middle layer that catches the exception that comes from each of the functions fire()in my commands? I was thinking about extending the class Command, but wanted to see if there was a way to do this that was recommended by the creators of the Framework (the documentation / search did not help).

, , .

?

+4
1

, , , . , .

Laravel Lumen Handler, . , - .

Laravel report() app/Exceptions/Handler.php, , . :

public function report(Exception $e)  
{
    if ($e instanceof CustomConsoleException) {
        // do something specific...
    }
    ...
}

renderForConsole() , . Handler , app/Exceptions/Handler.php :

public function renderForConsole($output, Exception $e)
{
    $output->writeln('Something broke!'); 

    (new ConsoleApplication)->renderException($e, $output);
}

$output Symfony\Component\Console\Output \OutputInterface, .

, uncaught, , , - . reportException() renderException() app/Console/Kernel.php.

- , , , , , . , , :

abstract class AbstractGetItems extends Command 
{
    ...
    final public function fire() 
    {
        try {
            $this->getItems();
        } catch (Exception $e) {
            // handle exception... 
        }
    }

    abstract protected function getItems();
}

getItems(), fire(). . - getItems(), :

class GetSpecificItems extends AbstractGetItems 
{ 
    ... 
    protected function getItems() 
    {
        // fetch specific items...
    }
}
+3

Source: https://habr.com/ru/post/1687759/


All Articles