Laravel7 - 检测到限制时在特定视图上重定向

Laravel7 - Redirect on specific view when throttling detected

我需要在登录期间检测到限制时将用户重定向到一个简单的信息视图。

我有一个名为 suspended.blade.php

的视图

我已经设置了路线

Route::get('/suspended', function(){
    return view('suspended');
});

我正在使用 Cartalyst/Sentinel.

在我的登录控制器中,我有这样的东西:

function LoginUser(Request $request){
   // some validation stuff...
  
   try {
     $user = Sentinel::authenticate($request->all());
   } catch (ThrottlingException $e) {
     // user inserted too many times a wrong password
     return redirect('/suspended');
   } catch (NotActivatedgException $e) {
     return redirect()->back()->with( ['error' => "Account not active yet."] );
   }

   // some other stuff...
}

如果我模拟 trottling,我只会得到一个错误页面,而不是我的视图。

这是为什么?

谢谢

编辑 按照@PsyLogic 的提示,我修改了我的函数:

function LoginUser(Request $request){
   // some validation stuff...
  
   try {
     $user = Sentinel::authenticate($request->all());
   } 
   /* remove this part to use the default behaviour described in app\Excpetions\Handler.php */
      // catch (ThrottlingException $e) {
      // return redirect('/suspended');
      // } 
   catch (NotActivatedgException $e) {
     return redirect()->back()->with( ['error' => "Account not active yet."] 
   );
 }

   // some other stuff...
}

仍然无效,并显示 Laravel 错误页面和所有调试代码。

Laravel 已经有 throttle 中间件你可以扩展它并更新 handle() 方法

namespace App\Http\Middleware;

use Illuminate\Routing\Middleware\ThrottleRequests;

class CustomThrottleMiddleware extends ThrottleRequests
{
     //...
}

并更新 Handle.php 文件中的新中间件

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
         // ...
        'throttle' =>App\Http\Middleware\CustomThrottleMiddleware::class,
]

或者您可以保留原始索引限制并添加您的 s

protected $routeMiddleware = [
            'auth' => \App\Http\Middleware\Authenticate::class,
             // ...
            'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
            'custom_throttle' =>App\Http\Middleware\CustomThrottleMiddleware::class,

    ]

已更新(简单方法)

即使这些更改不会影响您的包,但让我们用简单的方法来做,您可以更新 App\Exceptions\Handler::class 中的 render() 函数并进行测试

public function render($request, Throwable $exception)
    {
        if ($exception instanceof ThrottleRequestsException) {
            return redirect()->route('suspended'); 
        }

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