为了账号安全,请及时绑定邮箱和手机立即绑定

根据异常类型限制 Laravel 异常电子邮件通知

根据异常类型限制 Laravel 异常电子邮件通知

PHP
胡说叔叔 2023-09-22 16:55:37
有谁知道 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);    }}由于缺乏数据库中的跟踪,有没有一种方法可以通过异常类型来限制数据库错误,这样如果存在一致的数据库错误,我最终不会收到数千封电子邮件。我查看了Swift Mailer 的反洪水和节流插件,但这些插件会影响全局系统,这是我不想做的。先感谢您
查看完整描述

1 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

有几种方法可以实现这一目标。在派遣工作之前,您可以添加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 作业。


查看完整回答
反对 回复 2023-09-22
  • 1 回答
  • 0 关注
  • 50 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信