如何处理令牌不匹配异常 [英] How to handle Token Mismatch Exception
问题描述
我打开了Laravel表单,并将其保留了很长时间(5-6小时),或者使我的计算机处于休眠状态.长时间或从休眠状态恢复后,当我提交表单时,它会显示TokenMismatchException
.
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
.
我自己没有任何_token
字段.但是,Laravel会以每种形式添加_token
字段.看起来像这样:
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.
现在,如果令牌已过期,我想将我的应用程序重定向到登录页面或主页,或者显示自定义错误消息,而不是Laravel Token Mismatch
错误.
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.
推荐答案
所有异常均由App \ Exceptions \ Handler类处理
All exceptions are handled by the App\Exceptions\Handler class
请看一下 Laravel 5.1错误#render-方法 ,您会发现可以创建自定义
Exeption render
,检查以下示例中的TokenMismatchException
错误,该错误会将用户重定向到带有自定义消息的索引视图:
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);
}
希望这会有所帮助.
这篇关于如何处理令牌不匹配异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!