Laravel异常处理程序不捕获TokenMismatchException

时间:2017-05-09 09:39:44

标签: php laravel exception-handling

我试图在Laravel的Handler.php中捕获TokenMismatchException

当我通过暂时从表单中删除令牌来模仿csrf令牌例外时,我网站的本地开发版本会向我显示:

TokenMismatchException in VerifyCsrfToken.php line 68:

但是当我在Handler.php中更改render()函数以查找异常并处理错误时,它就不起作用了。例如,如果我用下面的默认代码替换以进行测试,并从表单中获取csrf令牌,系统会返回我的'这不是令牌问题'消息,而不是令牌问题'消息。

public function render($request, Exception $exception)
{
    if($exception instanceof TokenMismatchException) {
      return('token problem');
    }else{
      return('this was not a token problem');
    }
    return parent::render($request, $exception);
}

因此,使用默认代码Laravel似乎识别出TokenMismatchException,但是使用上面的简单测试代码,它没有。你能解释一下这里发生了什么吗?

1 个答案:

答案 0 :(得分:0)

可能会崩溃,因为返回期待来自render()的{​​{1}}

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{

    if($exception instanceof TokenMismatchException)
        return response()->json('Token mismatch');

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

请记住为异常使用正确的类

use Illuminate\Session\TokenMismatchException;

相关问题