在laravel 5中处理TokenMismatchException

Roh*_*kar 7 exception-handling exception laravel laravel-5

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

Hie*_* Le 23

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

例如,要在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);
}
Run Code Online (Sandbox Code Playgroud)


Mwi*_*Tim 8

您将需要编写一个函数来呈现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');
        }
Run Code Online (Sandbox Code Playgroud)