Laravel 限流信息

7

我正在使用ThrottleRequest来限制登录尝试次数。在Kendler.php中,我有以下代码:

'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

我的路由在web.php中

Route::post('login', ['middleware' => 'throttle:3,1', 'uses' => 'Auth\LoginController@authenticate']);

当我第四次登录时,它返回状态代码429并显示消息“TOO MANY REQUESTS”(默认情况下我想是这样)
但我只想返回错误消息,类似于:

return redirect('/login')
            ->withErrors(['errors' => 'xxxxxxx']);

有人能帮帮我吗!谢谢!

2个回答

10

您可以扩展中间件并覆盖 buildException() 方法来更改它在抛出 ThrottleRequestsException 时传递的消息,或者您可以使用自己的异常处理程序来捕获 ThrottleRequestsException 并执行任何您想要的操作。

因此,在 Exceptions/Handler.php 中,您可以执行类似以下操作:

use Illuminate\Http\Exceptions\ThrottleRequestsException;

public function render($request, Exception $exception)
{
    if ($exception instanceof ThrottleRequestsException) {
      //Do whatever you want here.
    }

    return parent::render($request, $exception);
}

哦,是的,我重写了buildException函数,现在它可以正常工作了。非常感谢你。 - hayumi kuran

1

或者自Laravel 8以来,您可以使用新的方式完成它:

app\exceptions\Handler.php中的register方法中可呈现。

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;

class Handler extends ExceptionHandler
 
/**
 * Register the exception handling callbacks for the application.
 */
public function register(): void
{
    // Create a renderable
    // see https://laravel.com/docs/10.x/errors#rendering-exceptions
    $this->renderable(function (ThrottleRequestsException $e) {
        return redirect('/login')
            ->withErrors(['errors' => 'xxxxxxx']);
    });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接