![](/img/trans.png)
[英]Why is Laravel 6.x creating a failed_jobs migration by default
[英]Is it possible to get last failed_jobs record id after Laravel job failed
我想為 failed_jobs 創建 GUI 並將它們與其他表記錄相關聯。 因此用戶可以知道在作業處理期間哪個作業屬性值失敗並可以重試。
Laravel Job 有一個函數failed(\\Exception $exception)
但它在異常之后但在記錄保存到 failed_jobs 表之前被調用。
Laravel 也有Queue:failing(FailedJob $job)
事件,但我只有序列化作業,但沒有 failed_jobs。
有沒有人遇到過類似的問題? 與處理的作業和失敗的作業有任何關系嗎?
在大驚小怪之后,我通過將相關模型嵌入到存儲到數據庫的 Exception 中來完成此操作。 您可以輕松地執行類似操作,但僅將 id 存儲在異常中,並在以后使用它來查找模型。 取決於你...
無論在何處發生使作業失敗的異常:
try {
doSomethingThatFails();
} catch (\Exception $e) {
throw new MyException(OtherModel::find($id), 'Some string error message.');
}
應用程序/異常/MyException.php:
<?php
namespace App\Exceptions;
use App\Models\OtherModel;
use Exception;
class MyException extends Exception
{
/**
* @var OtherModel
*/
private $otherModel = null;
/**
* Construct
*/
public function __construct(OtherModel $otherModel, string $message)
{
$this->otherModel = $otherModel;
parent::__construct(json_encode((object)[
'message' => $message,
'other_model' => $otherModel,
]));
}
/**
* Get OtherModel
*/
public function getOtherModel(): ?object
{
return $this->otherModel;
}
}
這將存儲一個包含對象的字符串到failed_jobs
表上的exception
列。 然后你只需要稍后解碼......
app/Models/FailedJob(或只是 app/FailedJob):
/**
* Return the human-readable message
*/
protected function getMessageAttribute(): string
{
if (!$payload = $this->getPayload()) {
return 'Unexpected error.';
}
$data = $this->decodeMyExceptionData();
return $data->message ?? '';
}
/**
* Return the related record
*/
protected function getRelatedRecordAttribute(): ?object
{
if (!$payload = $this->getPayload()) {
return null;
}
$data = $this->decodeMyExceptionData();
return $data->other_model ?? null;
}
/**
* Return the payload
*/
private function getPayload(): ?object
{
$payload = json_decode($this->payload);
return $payload ?? null;
}
/**
* Return the data encoded in a WashClubTransactionProcessingException
*/
private function decodeMyExceptionData(): ?object
{
$data = json_decode(preg_replace('/^App\\\Exceptions\\\WashClubTransactionProcessingException: ([^\n]*) in.*/s', '$1', $this->exception));
return $data ?? null;
}
任何地方:
$failedJob = FailedJob::find(1);
dd([
$failedJob->message,
$failedJob->related_record,
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.