Handle TokenMismatchException in laravel 5

前提是你 提交于 2019-12-17 15:35:12

问题


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.


回答1:


You can create a custom exception render in the App\Exceptions\Handler class (in the /app/Exceptions/Handler.php file).

For example, to render a different view when for the TokenMismatchException error, you can change the render method to something like this:

/**
 * 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);
}



回答2:


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:

// 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');
        }


来源:https://stackoverflow.com/questions/31846788/handle-tokenmismatchexception-in-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!