Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

DDSameera's avatar

How to customize throttle Error ?

If someone , enter 01 invalid password. he will block in 01 minute , I want to customize "too many login attempts" error message, so i added these codes. it doesn't work

api.php

  Route::group(['prefix' => 'user','middleware'=>['throttle:five_max_login_attempt_per_min']], function () {
       ........
    });
  try {
            //Authentication
            $isAuthenticatedUser = Auth::attempt(['email' => $loginRequest->input('email'), 'password' => $loginRequest->input('password')]);

            if (!$isAuthenticatedUser) {
                return SendResponseTrait::sendErrorWithToken('Invalid Email or Password', "Error", 401);

            }
        } catch (TooManyRequestsHttpException $tooManyRequestsHttpException) {
            return SendResponseTrait::sendErrorWithToken('Too Many Login Attempts. Please wait 01 minute', "Error", 422);

Error Screen

  "message": "Too Many Attempts.",
    "exception": "Illuminate\Http\Exceptions\ThrottleRequestsException",
    "file": "C:\wamp64\www\rmis\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
    "line": 200,
    "trace": [
        {
            "file": "C:\wamp64\www\rmis\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
            "line": 121,
            "function": "buildException",
            "class": "Illuminate\Routing\Middleware\ThrottleRequests",
            "type": "->"
        },
0 likes
5 replies
frankielee's avatar
Level 29

You can catch the issue at app/Exceptions/Handler.php

 public function render($request, Throwable $e)
 {

 if ($e instanceof \Illuminate\Http\Exceptions\ThrottleRequestsException)
{
	return here;
}


        return parent::render($request, $e);

}

1 like
DDSameera's avatar

@frankielee thanks . Actually I want to create separate exception class using php artisan make:exception TooManyLoginAttemptsException , then how can i handle this situation using that class ?

<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Http\Exceptions\ThrottleRequestsException;

class TooManyLoginAttemptsException extends Exception
{
  
}


frankielee's avatar

@ddsameera

Check your RouteServiceProvider.php

   protected function configureRateLimiting()
    {
     RateLimiter::for('test', function (Request $request) {
            return Limit::perMinute(5)->by(optional($request->user())->id ?: $request->ip())->response(function () {
               throw exceotion here

            });
       });
}
}

web.php

Route::post('login', "Auth\LoginController@login")->middleware('throttle:test');

frankielee's avatar

You can't throw your exception class there?

app/Http/Kernel.php, replace the throttle class with your class

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => TooManyLoginAttemptsException::class,
        //\Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
        'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
    ];

Your class, extend the ThrottleRequests instead. Customize the buildException function


use Illuminate\Routing\Middleware\ThrottleRequests;

class TooManyLoginAttemptsException extends ThrottleRequests{
protected function buildException($request, $key, $maxAttempts, $responseCallback = null)
    {
        $retryAfter = $this->getTimeUntilNextRetry($key);

        $headers = $this->getHeaders(
            $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts, $retryAfter),
            $retryAfter
        );
        return is_callable($responseCallback)
        ? new HttpResponseException($responseCallback($request, $headers))
        : new ThrottleRequestsException('Too Many Attempts.', null, $headers);

    }

}

Please or to participate in this conversation.