【问题标题】:Throttle Laravel Exception email notification per Exception type限制每个异常类型的 Laravel 异常电子邮件通知
【发布时间】:2020-11-30 09:57:12
【问题描述】:

有谁知道在 Laravel 中限制特定异常的电子邮件通知的方法?

当出现数据库错误时,我通过检查QueryException 让我的应用程序向我发送了一封电子邮件。这是我在 Laravel 的异常处理程序中所做的一个粗略示例:

class Handler{

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $e)
    {
        if($e instanceof QueryException){

            if( App::environment(['production']) ){
                Notification::route('mail', 'myemail@test.com')
                            ->notify(new DbErrorNotification($e));
            }
        }

        parent::report($e);
    }

}

在 DB 中缺少跟踪,有没有办法可以按异常类型限制 DB 错误,这样如果出现一致的 DB 错误,我最终不会收到数千封电子邮件。

我查看了Swift Mailer's anti-flood and throttling 插件,但它们会影响全局系统,我不想这样做。

提前谢谢你

【问题讨论】:

标签: php database laravel email swiftmailer


【解决方案1】:

有几种方法可以实现这一目标。在派遣工作之前,您可以在其上添加delay。示例:

use App\Http\Request;
use App\Jobs\SendEmail;
use App\Mail\VerifyEmail;
use Carbon\Carbon;

/**
 * Store a newly created resource in storage.
 *
 * @param Request $request
 * @return \Illuminate\Http\RedirectResponse
 * @throws \Symfony\Component\HttpKernel\Exception\HttpException
 */
public function store(Request $request)
{
    $baseDelay = json_encode(now());

    $getDelay = json_encode(
        cache('jobs.' . SendEmail::class, $baseDelay)
    );

    $setDelay = Carbon::parse(
        $getDelay->date
    )->addSeconds(10);

    cache([
        'jobs.' . SendEmail::class => json_encode($setDelay)
    ], 5);
    SendEmail::dispatch($user, new VerifyEmail($user))
         ->delay($setDelayTime);
}

或者,如果您不喜欢有关工作的想法,您也可以通过Mail 延迟它。示例:

Mail::to($user)->later($setDelayTime);

最后通过 Redis 速率限制。示例:

use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
/**
 * Execute the job.
 *
 * @return void
 */
public function handle()
{
    Redis::throttle('SendEmail')
        ->allow(1)
        ->every(10)
        ->then(function () {
            Mail::to($this->user)->send($this->mail);
        }, function () {
            return $this->release(10);
        });
}

允许每十秒发送一封电子邮件。传递给 throttle() 方法的字符串 SendEmail 是一个名称,用于唯一标识受速率限制的作业类型。您可以将其设置为任何您想要的。

release() 方法是作业类的继承成员,并且 指示 Laravel 将作业释放回队列中,并带有 如果无法获得锁,则可选延迟(以秒为单位)。 当作业被分派到队列时,Redis 被指示只 每十秒运行一个 SendEmail 作业。

请记住,对于所有这些,您需要一个 Redis

来源:https://medium.com/@bastones/a-simple-guide-to-queuing-mail-in-laravel-f4ff94cdaa59

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    相关资源
    最近更新 更多