【发布时间】:2015-08-06 04:20:54
【问题描述】:
我需要在 laravel 5 中处理 TokenMismatchException,这样如果令牌不匹配,它将向用户显示一些消息而不是 TokenMismatchException 错误。
【问题讨论】:
标签: laravel exception exception-handling laravel-5
我需要在 laravel 5 中处理 TokenMismatchException,这样如果令牌不匹配,它将向用户显示一些消息而不是 TokenMismatchException 错误。
【问题讨论】:
标签: laravel exception exception-handling laravel-5
您可以在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);
}
【讨论】:
if语句前加var_dump($e); die();,检查rendered方法是否被调用。
use Illuminate\Session\TokenMismatchException; 谢谢!
if ($e instanceof TokenMismatchException){ 而不是异常类的完整路径。
您需要编写一个函数来呈现 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){