Laravel 5.3 - 处理 NotFoundHttpException
Laravel 5.3 - Handling NotFoundHttpException
我正在使用 Laravel 5.3 并试图处理 render()
中来自 app\Exceptions\Handler.php
的所有常见异常。我想保存一个会话变量并自己在控制器中检查它。
例如:对于TokenMismatchException
,这样效果很好:
if($excp_class == 'Illuminate\Session\TokenMismatchException'){
return redirect($request->fullUrl())->with('TokenError', 'CSRF');
}
但是,对于 NotFoundHttpException
,我似乎无法让 Session 保存一个值。
if(stristr($excp_class, 'NotFoundHttpException')!=false)
{
//return redirect()->route('XYZRoute')->with('TokenError', 'NotFound'); //Also tried `withError`
\Request::session()->put('TokenError', 'NotFound'); //not working
\Request::session()->save();
return back();
}
我在这里错过了什么?
由于Laravel没有找到路由(NotFoundHttpException),您的请求没有通过中间件\Illuminate\Session\Middleware\StartSession。
那么您的请求没有会话。
如果你想让你所有的请求都有一个会话,你必须在内核的 $middleware 中添加 \Illuminate\Session\Middleware\StartSession::class:
namespace App\Http;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
];
...
}
我没有测试过,但我希望它能对你有所帮助。
我正在使用 Laravel 5.3 并试图处理 render()
中来自 app\Exceptions\Handler.php
的所有常见异常。我想保存一个会话变量并自己在控制器中检查它。
例如:对于TokenMismatchException
,这样效果很好:
if($excp_class == 'Illuminate\Session\TokenMismatchException'){
return redirect($request->fullUrl())->with('TokenError', 'CSRF');
}
但是,对于 NotFoundHttpException
,我似乎无法让 Session 保存一个值。
if(stristr($excp_class, 'NotFoundHttpException')!=false)
{
//return redirect()->route('XYZRoute')->with('TokenError', 'NotFound'); //Also tried `withError`
\Request::session()->put('TokenError', 'NotFound'); //not working
\Request::session()->save();
return back();
}
我在这里错过了什么?
由于Laravel没有找到路由(NotFoundHttpException),您的请求没有通过中间件\Illuminate\Session\Middleware\StartSession。 那么您的请求没有会话。
如果你想让你所有的请求都有一个会话,你必须在内核的 $middleware 中添加 \Illuminate\Session\Middleware\StartSession::class:
namespace App\Http;
class Kernel extends HttpKernel {
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
];
...
}
我没有测试过,但我希望它能对你有所帮助。