![](/img/trans.png)
[英]The failed() method is not being called when an Job fails in Laravel 5.4
[英]How to trigger laravel jobs failed() method when job fails?
目前我正在調用任務Report.php
並使用generateReport()
方法生成報告。 我已經檢查了使用CLI命令php artsan queue:listen
執行的作業。 如果在調用Artisan::call()
出現任何問題,則錯誤消息將顯示在終端中。 所以我想在failed()
捕獲異常,我想將錯誤記錄到日志中。 我已嘗試使用handle()
方法中的try catch
但它沒有捕獲異常。
protected $options;
public function __construct($options)
{
$this->options = array_merge(
[
'task' => 'Report',
'do' => 'generateReport',
'limit' => '10000'
],
$options
);
}
public function handle()
{
Artisan::call('execute', [
'--task' => $this->options['task'],
'--do' => $this->options['do'],
'--parameters' => $this->options,
]);
}
public function failed()
{
//
}
如何觸發failed()
並將錯誤記錄到日志中?
Artisan::call
實際上只是調用execute
控制台類,所以如果你在那里拋出Exception
,它應該自動以failed
方法結束。
但是,在5.2
, Exception
對象不會傳遞給失敗的方法(這是在5.3
中添加的)。
Laravel 5.2
因此,如果您需要將Exception
對象傳遞給failed
方法,那么您需要在5.2
:
public function handle()
{
try {
Artisan::call('execute', [
'--task' => $this->options['task'],
'--do' => $this->options['do'],
'--parameters' => $this->options,
]);
} catch (\Exception $e) {
$this->failed($e)
}
}
public function failed(\Exception $e = null)
{
//handle error
}
Laravel 5.3+
在5.3
, Exception
會自動傳遞給failed
因此您的代碼將如下所示:
public function handle()
{
Artisan::call('execute', [
'--task' => $this->options['task'],
'--do' => $this->options['do'],
'--parameters' => $this->options,
]);
}
public function failed(\Exception $e = null)
{
//handle error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.