我有一份工作是用来测试失败是如何运作的:
<?php
namespace App\Jobs;
use App\ApiUser;
use App\Helpers\Helper;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class FakeJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $apiUser;
public function __construct(ApiUser $apiUser) {
$this->apiUser = $apiUser;
}
public function handle() {
throw new Exception('time is even');
}
public function failed(Exception $exception) {
// Send user notification of failure, etc...
$path = storage_path('logs/s3_logs/FakeJob_failed_' . Helper::generateRandomString(5) . '.txt');
file_put_contents($path, $exception->getMessage());
}
}
当我正常分派时,它会按预期的方式传递到failed
函数并写入文件。
然而,当我像FakeJob::dispatchNow($apiUser);
那样做的时候,它根本就不会那么做.
是否有一种方法可以在与请求相同的进程上运行,但在正常排队的情况下失败呢?
因为目前看来,我唯一的方法是做这样的事:
$fakeJob = new FakeJob($apiUser);
try {
$fakeJob->handle();
} catch(Exception $e) {
$fakeJob->failed($e);
}
这是..。好吧,我想,但不太理想。
发布于 2020-01-03 13:44:53
如果我没有错,dispatchNow()用于同步运行作业,但不幸的是,它没有调用失败的方法。
如果希望在作业失败时调用失败的方法,则可以使用以下代码。
FakeJob::dispatch($apiUser)->onConnection('sync');
它将同步运行作业,并执行失败的方法。
发布于 2020-07-22 08:33:57
一个新的dispatchSync()
方法将在未来几个月发布时在Laravel8.0中提供。
它将像@Keshari的answer建议的那样,在同步队列上分派作业。
博士:https://laravel.com/docs/master/queues#synchronous-dispatching
提交:https://github.com/laravel/framework/commit/0b3ed6859046258fba2e0ab3340bdab33e4c82bd
发布于 2020-01-03 13:22:20
查看Laravel代码库(和docs),dispatchNow()
方法在不与任何队列交互的情况下同步执行作业。
https://laravel.com/docs/5.8/queues#synchronous-dispatching
本质上,它只是在工作中调用handle()
方法,仅此而已。
您所做的尝试/捕捉块可能是目前最好的解决方案,但值得向Laravel团队提出这一特性请求。
https://stackoverflow.com/questions/59578987
复制相似问题