簡體   English   中英

如何翻譯 laravel 中的油門?

[英]how to translate throttle in laravel?

我正在使用 Laravel 5.7 版本。 我在Kernel.php中使用throttle來避免用戶發送超過 60 個查詢。我想翻譯它的消息“嘗試次數過多”。 並使用自己的消息。 我該如何在 laravel 中做到這一點? 我在哪里可以找到那個?

在您的 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);
}

您可以在app/Http/Middlewares文件夾中創建自定義中間件,擴展基礎\Illuminate\Routing\Middleware\ThrottleRequests class 並覆蓋buildException方法( 此處為原始實現)。

然后將throttle中間件分配給 Kernel.php 中的自定義中間件Kernel.php



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());
}


我在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
        );
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM