为什么 Laravel 作业控制台 returns 失败但已发送电子邮件

Why Laravel Jobs console returns failed but email is sent

我不明白为什么我在控制台中的 php artisan queue:work 命令 returns 失败了,但是电子邮件已发送并且只触发了第一个函数调用。

public function handle()
{
    //1st email
    $this->sendto_client($this->request,$this->totalprodprice,$this->quotationprice,$this->featitem,$this->quoteid);

    //2nd email
    $this->sendto_branches($this->request,$this->totalprodprice,$this->quotationprice,$this->featitem,$this->quoteid);
}

这是我的调度方法:

$job1 = new SendQuoteEmail(collect($request),$totalprodprice,$quotationprice,$featitem,$quoteid,"client");
$this->dispatch($job1);

这是一些控制台日志。

[2022-02-15 23:50:04][28] Processing: App\Jobs\SendQuoteEmail
[2022-02-15 23:50:08][28] Failed:     App\Jobs\SendQuoteEmail

即使邮件已发送,您的工作仍然失败,因为您在 Mail 触发后编写的代码抛出异常

对于示例 让我们考虑以下Job Class

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class FailedJobWithPartialSuccessJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //this will work

        logger()->info('My Log message before Exception');

        //Your other logic

        throw new \Exception("Message is Logged before the Exception but the job is failed", 1);

        //code below the exception won't work

        logger()->info('My Log message after Exception');
        
    }
}

像这样分派作业 FailedJobWithPartialSuccessJob::dispatch() 并盯着这里的工人是我的 cli 输出

这是日志文件内容

[2022-02-16 05:00:21] local.INFO: My Log message before Exception  
[2022-02-16 05:00:21] local.ERROR: Message is Logged before the Exception but the job is failed {"exception":"[object] (Exception(code: 1): Message is Logged before the Exception but the job is failed at C:\xampp\htdocs\serverinventory\app\Jobs\FailedJobWithPartialSuccessJob.php:39)
[stacktrace]
#0 C:\xampp\htdocs\serverinventory\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(36): App\Jobs\FailedJobWithPartialSuccessJob->handle()
"} 

即使作业处理失败,您也可以看到 Exception 执行之前的部分