diff --git a/src/TaskRunner.php b/src/TaskRunner.php index c41a0d2..914d526 100644 --- a/src/TaskRunner.php +++ b/src/TaskRunner.php @@ -139,7 +139,13 @@ protected function updateLogs(TaskLog $taskLog) } // "unique" name will be returned if one wasn't set - $name = $taskLog->task->name; + $name = $taskLog->task->name; + $error = null; + + if ($taskLog->error instanceof Throwable) { + $error = "Exception: {$taskLog->error->getCode()} - {$taskLog->error->getMessage()}" . PHP_EOL . + "file: {$taskLog->error->getFile()}:{$taskLog->error->getLine()}"; + } $data = [ 'task' => $name, @@ -147,7 +153,7 @@ protected function updateLogs(TaskLog $taskLog) 'start' => $taskLog->runStart->format('Y-m-d H:i:s'), 'duration' => $taskLog->duration(), 'output' => $taskLog->output ?? null, - 'error' => serialize($taskLog->error ?? null), + 'error' => $error, ]; // Get existing logs diff --git a/tests/unit/TaskRunnerTest.php b/tests/unit/TaskRunnerTest.php index 8a2ae5e..15c33a1 100644 --- a/tests/unit/TaskRunnerTest.php +++ b/tests/unit/TaskRunnerTest.php @@ -66,7 +66,7 @@ public function testRunWithSuccess() 'start' => date('Y-m-d H:i:s'), 'duration' => '0.00', 'output' => null, - 'error' => serialize(null), + 'error' => null, ], ]; $this->seeInDatabase('settings', [ @@ -79,6 +79,53 @@ public function testRunWithSuccess() ]); } + /** + * @throws ReflectionException + */ + public function testRunWithError() + { + $task1 = (new Task('closure', static function () { + echo 'Task 1'; + }))->daily('12:05am')->named('task1'); + $task3 = (new Task('closure', static function () { + throw new Exception('Example exception in Task 3'); + }))->daily('12:00am')->named('task3'); + + $runner = $this->getRunner([$task1, $task3]); + + ob_start(); + $runner->withTestTime('12:00am')->run(); + $output = ob_get_clean(); + + // Only task 3 should have run + $this->assertSame('', $output); + + // Get info about the exception + $reflection = new ReflectionFunction($task3->getAction()); + $file = $reflection->getFileName(); + $line = $reflection->getStartLine() + 1; + + // Should have logged the stats + $expected = [ + [ + 'task' => 'task3', + 'type' => 'closure', + 'start' => date('Y-m-d H:i:s'), + 'duration' => '0.00', + 'output' => null, + 'error' => "Exception: 0 - Example exception in Task 3\nfile: {$file}:{$line}", + ], + ]; + $this->seeInDatabase('settings', [ + 'class' => 'CodeIgniter\Tasks\Config\Tasks', + 'key' => 'log-task3', + 'value' => serialize($expected), + ]); + $this->dontSeeInDatabase('settings', [ + 'key' => 'log-task1', + ]); + } + protected function getRunner(array $tasks = []) { $scheduler = service('scheduler');