处理laravel 5中的令牌不匹配异常

处理laravel 5中的令牌不匹配异常,laravel,exception,exception-handling,laravel-5,Laravel,Exception,Exception Handling,Laravel 5,我需要在laravel 5中处理令牌不匹配异常,如果令牌不匹配,它将向用户显示一些消息,而不是令牌不匹配异常错误。您可以在App\Exceptions\Handler类(在/App/Exceptions/Handler.php文件中)中创建自定义 例如,要在出现tokenmischException错误时呈现不同的视图,您可以将render方法更改为如下所示: /** * Render an exception into an HTTP response. * * @param \Ill

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

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

例如,要在出现
tokenmischException
错误时呈现不同的视图,您可以将
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);
}

您需要编写一个函数来呈现令牌不匹配异常错误。您将通过以下方式将该函数添加到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');
        }

嗨,邱。刚刚尝试了您的方法,但不幸的是,每当我发布一个假的csrf令牌/Can you add
var_dump($e)时,我仍然会得到一个“VerifyCsrfToken.php第53行中的令牌失配异常”;模具()
if
语句之前,检查是否调用了
rendered
方法。是的,现在我得到了对象的脏页转储(illumb\Session\tokenmischexception)#274…现在我只是通过在App\exceptionhandler.php类上添加名称空间来修复它-
使用illumb\Session\tokenmischexception谢谢!我刚刚注意到我的错误是执行
if($e instanceof tokenmischException){
而不是异常类的完整路径。谢谢,这是有效的,只是实例必须具有完整路径:
if($exception instanceof\illumb\Session\tokenmischException){
注意,我在顶部引用了类的完整路径。我们可以通过在刷新令牌后重新提交包含数据的表单来扩展此行为吗?