不同视图组的自定义错误页面

时间:2018-02-06 12:37:54

标签: php laravel laravel-5

我的应用程序有一个登录页面和一个管理面板。所以,我想为这些视图创建不同的404页面。我的views文件夹有2个文件夹:adminsite,其中我有errors个文件夹,其中包含已创建的404.blade.php个文件。为了实现我的目标,我在renderHttpException(HttpException $e)中覆盖了一个名为app/Exceptions/Handler.php的方法,但遗憾的是它不起作用。解决方法是什么?

以下是renderHttpException(HttpException $e)方法:

protected function renderHttpException(HttpException $e) 
{
    $status = $e->getStatusCode();

    if(Request::is('/admin/*')) { 
        return response()->view("admin/errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }else {
        return response()->view("site/errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }    
}

还有路线:

/* Site routes */
Route::get('/', 'HomeController@index')->name('home');
Route::get('/menu', 'MenuController@index')->name('menu');

/* Admin panel routes */
Route::prefix('/admin')->namespace('Admin')->group(function () {
    Route::get('/', 'HomeController@index')->name('admin-dashboard');
    Route::get('/login', 'HomeController@showLoginForm')->name('admin-login');
    Route::get('/menu', 'MenuController@index')->name('admin-menu');
});

因此会抛出错误:

  

App \ Exceptions \ Handler :: renderHttpException(App \ Exceptions \ HttpException $ e)的声明应该与Illuminate \ Foundation \ Exceptions \ Handler :: renderHttpException兼容(Symfony \ Component \ HttpKernel \ Exception \ HttpException $ e)< / p>

1 个答案:

答案 0 :(得分:2)

将其放在\ App \ Exceptions \ Handler :: render

if($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
    $view = $request->is('admin/*') ? 'admin/errors.404' : 'site/errors.404' ;

    return response()->view($view, [], 404);
}

所以你的方法应该是这样的:

public function render($request, Exception $exception)
{
    if($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
        $view = $request->is('admin/*') ? 'admin/errors.404' : 'site/errors.404' ;

        return response()->view($view, [], 404);
    }


    $e = $this->prepareException($exception);

    if ($e instanceof FlashingException) {
        return $e->getResponse();
    }
    return parent::render($request, $exception);
}