为什么“onFailure”钩子不提供任何输出(Laravel任务计划程序)?

Why "onFailure" hook is not providing any output (Laravel Task Scheduler)?

提问人:Boulteu 提问时间:5/5/2023 最后编辑:Boulteu 更新时间:5/7/2023 访问量:309

问:

使用 Laravel 10.9,我有一个控制器 TestController,其方法测试如下:

public function test() {
    throw new \Exception('this is an error');
}

Console\Kernel 中,我有一个这样的计划任务:

$schedule->call(function() {
    $instance = new TestController();
    $instance->test();
})->everyMinute()
  ->onSuccess(function() {
    dd('ok');
})->onFailure(function(\Exception $e) {
    dd('failed: ' . $e->getMessage());
});

我知道我的计划任务失败了,因为我收到“失败:”消息,但为什么什么都不返回?它应该返回“失败:这是一个错误”,但它只返回“失败:”$e->getMessage()

php laravel 异常 调度任务 laravel-10

评论

1赞 Snapey 5/6/2023
文档中没有任何内容可以说您可以将异常实例传递到 onFailure 闭包中?
0赞 Boulteu 5/7/2023
@Snapey laravel.com/docs/10.x/scheduling#task-hooks 这里写的“如果你的命令有输出,你可以通过键入提示 Illuminate\Support\Stringable 实例作为钩子闭包定义$output参数,在 after、onSuccess 或 onFailure 钩子中访问它”,但对于 Stringable 实例,它不起作用......
1赞 Snapey 5/7/2023
你必须从你的任务中输出一个字符串,而不是一个例外?

答:

1赞 Snapey 5/7/2023 #1

如果创建控制台命令而不是控制器类,则可以捕获输出。

php artisan make:command test

app\Console\Commands\test.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Test extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Its just a test';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->error('something went wrong');

        return Command::FAILURE;
    }
}

然后在Kernel.php


        $schedule->command('test')->everyMinute()
          ->onSuccess(function() {
            dd('ok');
        })->onFailure(function(Stringable $output) {
            dd('failed: ' . $output);
        });

这将输出“失败:出错”

评论

0赞 Boulteu 5/7/2023
所以它仅适用于 $schedule->命令,而不适用于 $schedule->call ?
1赞 Snapey 5/7/2023
您无法从控制器返回错误和消息
0赞 Boulteu 5/7/2023
我不想从控制器返回错误和消息,我想在从控制器(甚至从简单类)调度方法时抛出异常,并在“onFailure”方法中得到此异常
1赞 Snapey 5/8/2023
不要将控制器用于明显不是 Http 请求的内容
1赞 Snapey 5/9/2023
忘记 onFailure 方法。这是为了检测返回代码和控制台输出。相反,将 包装在常规的 try-catch 块中。在课堂上抛出一个异常,并在kernel.php中捕获它。schedule->call