How to handle Token Mismatch Exception

2020-06-06 01:47发布

问题:

I opened a Laravel form and left it as it is for long time (5-6 hours) or hibernated my computer. After long time or after resuming from hibernate when I submit the form it shows a TokenMismatchException.

I don't have any _token field by my own. But a _token field is added by Laravel in every form. It looks like this:

<input name="_token" type="hidden" value="YLyMGdfLKZESo51SYUHLKAzC6MNRLOQc9D9e2RFq">

I understand there is some token expiry issue, but it is bad to show a client an error message like this.

Now, I want to redirect my application to the login page or home page if the token is expired, or show a custom error message instead of a Laravel Token Mismatch error.

Note: I don't want to increase token expire time.

回答1:

All exceptions are handled by the App\Exceptions\Handler class

Taka a look at Laravel 5.1 errors#render-method you will find that you can create a custom Exeption render, check the following example for the TokenMismatchException error, that will redirect the user to index view with custom message :

public function render($request, Exception $e)
{
    if ($e instanceof \Illuminate\Session\TokenMismatchException) {
        return response()->view('index', ['message' => 'custom message'], 500);
    }
    return parent::render($request, $e);
}

Hope this helps.



回答2:

I haven't made my way up to Laravel 5.1 yet, but as of 4.2, I used something like this to handle token mismatch errors in app/start/global.php:

App::error(function(Exception $exception, $code)
{
    // if they get token mismatch, redirect to homepage
    if( strpos($exception->__toString(), 'Illuminate\Session\TokenMismatchException') !== false ){
        return Redirect::route('getHome')->with('notice', Lang::get('messages.sessionExpired'));
    }

    // rest of error handling...
});

I'd imagine this would need some modification for Laravel 5.1, but I hope it helps you get on the right track!

Here are some links that will probably help you:

  • Laravel catch TokenMismatchException
  • Handle TokenMismatchException in laravel 5
  • http://laravel.com/docs/5.1/errors#the-exception-handler