I am using Laravel 5.5. There is following class
vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php
with Method Name: buildException
In, Laravel 5.4, I was able to return JSON in this method like below.
protected function buildException($key, $maxAttempts)
{
$retryAfter = $this->getTimeUntilNextRetry($key);
$headers = $this->getHeaders(
$maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
$retryAfter
);
return response()->json('429 Too many requests');
}
When I try to return JSON in above method using Laravel 5.5, it says
Cannot throw objects that do not implement Throwable
Now sure , how could I return JSON in Laravel 5.5 for above method
Well, you cannot do it like this now any more. You need to return exception class. But what you can do is returning some custom exception class and then in app/Exceptions/Handler.php
in `render method you can add:
if ($e instanceof YourCustomException) {
return response()->json('429 Too many requests');
}
Of course if you really need, you can add your own implementation of handle
method and instead of throwing exception you can return response directly in there but probably throwing custom exception and handling it in Handler class is better choice.