[英]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.