【问题标题】:Handle TokenMismatchException for ajax request处理 ajax 请求的 TokenMismatchException
【发布时间】:2018-11-21 10:55:23
【问题描述】:

我正在使用 ajax 将请求发送到服务器,有时我可能会在服务器上收到 TokenMismatchException。现在,我想在后端和前端都处理这个问题。为此,我使用了来自this StackOverflow link 的参考:

public function render($request , Exception $exception)
{
    //TODO Check the following if() block code validity for production server
    if ($exception instanceof \Illuminate\Session\TokenMismatchException){
        if ($request->expectsJson() ){
            return Response::json([
                'message'      => 'Token mismatch (CSRF token mismatched)' ,
                'message-type' => 'danger' ,
                'new_csrf_token' => csrf_token()
            ], $exception->getStatusCode());
        }
        return redirect()
            ->back()
            ->exceptInput('password')
            ->with([
                'message'      => 'Validation Token was expired. Please try again' ,
                'message-type' => 'danger' ,
            ]);
    }

    return parent::render($request , $exception);
}

使用这个 JSON 响应,我想在前端显示一条提示消息,并更新 CSRF 令牌以重新发送请求。

但我收到一条错误消息:

调用未定义的方法 Illuminate\Session\TokenMismatchException::getStatusCode()

任何想法如何处理这个 ajax 请求异常?

【问题讨论】:

    标签: php json ajax laravel request-response


    【解决方案1】:

    TokenMismatchException 是一个非 Http 异常,因此它不会返回它的状态码。您可以根据需要重定向到所需的视图或登录页面。

    【讨论】:

      【解决方案2】:

      Laravel token 未匹配异常码是419,可以直接用419代替$exception->getStatusCode()

      【讨论】:

      • 代码 419 不对应此链接中所述的任何状态:restapitutorial.com/httpstatuscodes.html。用这个状态码好不好?
      • 是的,但是 laravel 使用这个代码,elseif ($e instanceof TokenMismatchException) { $e = new HttpException(419, $e->getMessage(), $e); } 请检查vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php line 203
      猜你喜欢
      • 2014-03-04
      • 2016-10-12
      • 2019-11-20
      • 2015-08-04
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      相关资源
      最近更新 更多