1

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

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Pankaj
  • 9,749
  • 32
  • 139
  • 283

1 Answers1

2

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.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • Can u please give more details with example about YourCustomException in both places(ThrottleRequests and Handler.php) – Pankaj Sep 27 '17 at 21:50
  • You can create custom class that extends `Symfony\Component\HttpKernel\Exception\HttpException`, in `buildException` method throw this exception and than in Handler use `if ($e instanceof YourCustomException) {` – Marcin Nabiałek Sep 27 '17 at 22:09