提问人:Boulteu 提问时间:5/5/2023 最后编辑:Boulteu 更新时间:5/7/2023 访问量:309
为什么“onFailure”钩子不提供任何输出(Laravel任务计划程序)?
Why "onFailure" hook is not providing any output (Laravel Task Scheduler)?
问:
使用 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()
答:
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
评论