处理 Laravel 5 中的 TokenMismatchException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31846788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle TokenMismatchException in laravel 5
提问by Rohit Pavaskar
I need to handle TokenMismatchException
in laravel 5 such a way that if token does not match it will show some message to user instead of TokenMismatchException
error.
我需要TokenMismatchException
在 laravel 5 中处理这样一种方式,如果令牌不匹配,它将向用户显示一些消息而不是TokenMismatchException
错误。
回答by Hieu Le
You can create a custom exception renderin the App\Exceptions\Handler
class (in the /app/Exceptions/Handler.php
file).
您可以在类中(在文件中)创建自定义异常渲染。App\Exceptions\Handler
/app/Exceptions/Handler.php
For example, to render a different view when for the TokenMismatchException
error, you can change the render
method to something like this:
例如,要在TokenMismatchException
出现错误时呈现不同的视图,您可以将render
方法更改为如下所示:
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof \Illuminate\Session\TokenMismatchException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $e);
}
回答by Mwirabua Tim
You will need to write a function to render the TokenMismatchException error. You will add that function to your App\Exceptions\Handler class (in the /app/Exceptions/Handler.php file) this way:
您将需要编写一个函数来呈现 TokenMismatchException 错误。您将通过这种方式将该函数添加到您的 App\Exceptions\Handler 类(在 /app/Exceptions/Handler.php 文件中):
// make sure you reference the full path of the class:
use Illuminate\Session\TokenMismatchException;
class Handler extends ExceptionHandler {
protected $dontReport = [
HttpException::class,
ModelNotFoundException::class,
// opt from logging this error to your log files (optional)
TokenMismatchException::class,
];
public function render($request, Exception $e)
{
// Handle the exception...
// redirect back with form input except the _token (forcing a new token to be generated)
if ($e instanceof TokenMismatchException){
return redirect()->back()->withInput($request->except('_token'))
->withFlashDanger('You page session expired. Please try again');
}