在Laravel作业失败后,是否可以获得最后一次failed_jobs记录ID

时间:2018-01-09 17:02:49

标签: php laravel

我想为failed_jobs创建GUI并将它们与其他表记录相关联。因此,用户可以知道在作业处理期间哪些作业属性值失败,并且可以重试。

Laravel Job有一个函数failed(\Exception $exception),但是在异常之后但在记录保存在failed_jobs表之前调用它。

Laravel也有Queue:failing(FailedJob $job)事件,但我只有序列化的工作,但没有失败的工作。

有没有人遇到过类似的问题?是否与处理过的作业有关系并且失败了?

1 个答案:

答案 0 :(得分:0)

大惊小怪之后,我通过将相关模型嵌入存储在数据库中的Exception中来完成此操作。您可以轻松地执行类似操作,但仅将ID存储在异常中,并在以后使用它查找模型。由你决定...

无论何时发生使作业失败的异常:

try {
    doSomethingThatFails();
} catch (\Exception $e) {
    throw new MyException(OtherModel::find($id), 'Some string error message.');
}

app / Exceptions / 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;
    }
}

这会将包含对象的字符串存储到exception表的failed_jobs列中。然后,您只需要稍后对其进行解码...

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,
]);