Laravel 作业失败后是否可以获取最后一个 failed_jobs 记录 id

2024-04-22

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

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

Laravel 还有Queue:failing(FailedJob $job)事件,但我只有序列化作业,但没有 failed_jobs。

有人遇到过类似的问题吗?与已处理的作业和失败的作业有任何关系吗?


经过一番周折之后,我通过将相关模型嵌入到存储到数据库的异常中来完成此任务。您可以轻松执行类似的操作,但仅将 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;
    }
}

这会将包含对象的字符串存储到exception列于failed_jobs桌子。然后你只需要稍后解码......

应用程序/模型/失败作业(或只是应用程序/失败作业):

    /**
     * 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,
]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 作业失败后是否可以获取最后一个 failed_jobs 记录 id 的相关文章

随机推荐