【问题标题】:Handle TokenMismatchException in laravel 5在 laravel 5 中处理 TokenMismatchException
【发布时间】:2015-08-06 04:20:54
【问题描述】:

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

【问题讨论】:

    标签: laravel exception exception-handling laravel-5


    【解决方案1】:

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

    例如,要在出现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);
    }
    

    【讨论】:

    • 嗨嗨。刚刚尝试了你的方法,不幸的是,每当我发布一个假的 csrf 令牌/
    • 能否在if语句前加var_dump($e); die();,检查rendered方法是否被调用。
    • 是的,现在我得到了 object(Illuminate\Session\TokenMismatchException)#274 的脏页转储 ...
    • 现在我只是通过在 App\ExceptionsHandler.php 类上添加命名空间来修复它 - use Illuminate\Session\TokenMismatchException; 谢谢!
    • 我刚刚注意到我的错误是使用if ($e instanceof TokenMismatchException){ 而不是异常类的完整路径。
    【解决方案2】:

    您需要编写一个函数来呈现 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');
            }
    

    【讨论】:

    • 谢谢,除了实例必须有完整路径之外,这是可行的:if ($exception instanceof \Illuminate\Session\TokenMismatchException){
    • 请注意,我在顶部引用了类的完整路径
    • 我们可以通过在令牌刷新后重新提交带有数据的表单来扩展此行为吗?
    猜你喜欢
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2015-08-10
    相关资源
    最近更新 更多