Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jivkim's avatar

Task scheduling: Cannot catch Exception when cron is invalid - Laravel 9

Hi!

I'm having trouble catching "InvalidArgumentException" thrown from "dragonmantank\cron-expression\src\Cron\CronExpression" when scheduling a job.

My App\Console\Kernel is iterating over multiple entries and schedules a job for each, with a cron notation that comes from a user interface. If a cron is invalid, the next jobs are ignored because of the exception. This is why I put a try catch but unfortunately the exception is not catched, I can't understand why.

Simplified example with an on-purpose invalid cron:

// app\Console\Kernel.php
    protected function schedule(Schedule $schedule)
    {
        try {
            $schedule->call(function(){
                echo "Hello";
            })->cron("/5 * * * *");
        } catch (InvalidArgumentException $e) {
            echo $e->getMessage();
        }
    }

The output of php artisan schedule:run:

InvalidArgumentException 

  Invalid CRON field value /5 at position 0

  at C:\Users\perezj\dev\reporter\vendor\dragonmantank\cron-expression\src\Cron\CronExpression.php:231
    227▕      */
    228▕     public function setPart(int $position, string $value): CronExpression
    229▕     {
    230▕         if (!$this->fieldFactory->getField($position)->validate($value)) {
  ➜ 231▕             throw new InvalidArgumentException(
    232▕                 'Invalid CRON field value ' . $value . ' at position ' . $position
    233▕             );
    234▕         }
    235▕

  1   C:\Users\perezj\dev\reporter\vendor\dragonmantank\cron-expression\src\Cron\CronExpression.php:212
      Cron\CronExpression::setPart()

  2   C:\Users\perezj\dev\reporter\vendor\dragonmantank\cron-expression\src\Cron\CronExpression.php:187
      Cron\CronExpression::setExpression()

I've also tried:

        $schedule->call(function(){
            echo "Hello";
        })->cron("/5 * * * *")->onFailure(function(){
            echo "Failed";
        });

But it's the same.

For the record, I have a validation of the cron from the user interface, but it considers /5 * * * * to be valid, but Laravel does not.

Any idea on how to catch the error ? Am I missing something ?

Thanks

0 likes
2 replies
Snapey's avatar

You could test the value

    try {
        $cron = new CronExpression('/5 * * * *'); 
    } catch (InvalidArgumentException $e) {
        echo $e->getMessage();
        // Handle the exception or log it as required
    }
    
    $schedule->call(function(){
        echo "Hello";
    })->cron("/5 * * * *");

or better, validate the input using the same technique to catch errors on input, not at run time.

1 like

Please or to participate in this conversation.