处理 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:07:51  来源:igfitidea点击:

Handle TokenMismatchException in laravel 5

laravelexceptionexception-handlinglaravel-5

提问by Rohit Pavaskar

I need to handle TokenMismatchExceptionin laravel 5 such a way that if token does not match it will show some message to user instead of TokenMismatchExceptionerror.

我需要TokenMismatchException在 laravel 5 中处理这样一种方式,如果令牌不匹配,它将向用户显示一些消息而不是TokenMismatchException错误。

回答by Hieu Le

You can create a custom exception renderin the App\Exceptions\Handlerclass (in the /app/Exceptions/Handler.phpfile).

您可以在类中(在文件中)创建自定义异常渲染App\Exceptions\Handler/app/Exceptions/Handler.php

For example, to render a different view when for the TokenMismatchExceptionerror, you can change the rendermethod 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');
        }