【问题标题】:how to translate throttle in laravel?如何在laravel中翻译节流阀?
【发布时间】:2020-01-22 16:24:59
【问题描述】:

我使用的是 Laravel 5.7 版本。我在Kernel.php 中使用throttle 来避免用户发送超过60 个查询。我想翻译它的消息“Too Many Attempts”。并使用自己的消息。我怎样才能在laravel中做到这一点?我在哪里可以找到那个?

【问题讨论】:

    标签: php laravel throttling


    【解决方案1】:
    
    
    use Symfony\Component\HttpKernel\Exception\HttpException;
    
    if($exception instanceof HttpException && $exception->getStatusCode() == 429) {
    return response()->json([
    'message' => 'Too Many Attempts',
    'code' => 429
    ], 429)->withHeaders($exception->getHeaders());
    }
    
    
    

    【讨论】:

      【解决方案2】:

      在您的 Laravel 异常处理程序中,您可以在渲染之前处理该异常并将该异常替换为您的自定义异常。

      app/Exceptions/Handler.php

      /**
       * Render an exception into an HTTP response.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Exception  $exception
       * @return \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
       */
      public function render($request, Exception $exception)
      {
          if($exception instanceof ThrottleRequestsException) {
              return parent::render(
                  $request, new ThrottleRequestsException(
                      'Your message',
                      $exception->getPrevious(),
                      $exception->getHeaders(),
                      $exception->getCode()
                  )
              );
          }
      
          return parent::render($request, $exception);
      }
      

      【讨论】:

        【解决方案3】:

        您可以在 app/Http/Middlewares 文件夹中创建自定义中间件,扩展基础 \Illuminate\Routing\Middleware\ThrottleRequests 类并覆盖 buildException 方法 (original implementation here)。

        然后将throttle中间件分配给Kernel.php中的自定义中间件类

        【讨论】:

          【解决方案4】:

          我在 Laravel 的这个地址找到了它的文件: vendor\laravel\framework\src\llluminate\Routing\Middleware\ThrottleRequests.php

          protected function buildException($key, $maxAttempts)
              {
                  $retryAfter = $this->getTimeUntilNextRetry($key);
          
                  $headers = $this->getHeaders(
                      $maxAttempts,
                      $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
                      $retryAfter
                  );
          
                  return new ThrottleRequestsException(
                      'You can change message here and put your message!', null, $headers
                  );
              }
          

          【讨论】:

          • 我建议不要编辑核心框架/包文件,它们可能会在更新后消失
          猜你喜欢
          • 1970-01-01
          • 2021-12-10
          • 2018-10-23
          • 2012-05-11
          • 2020-08-02
          • 1970-01-01
          • 2023-03-20
          • 2017-03-22
          • 2016-10-05
          相关资源
          最近更新 更多