Laravel不同的404页面用于不同的名称空间/路由组

问题描述:

我在Laravel中有三个不同的Http名称空间:Frontend,Backend和API.每个路由组还有一个不同的名称空间.这是RouteServiceProvider的示例代码(前端路由组):

I have three different Http namespaces in Laravel: Frontend, Backend, and API. There is also a different namespace for each route group. Here is an example code (frontend route group) from RouteServiceProvider:

protected function mapFrontendRoutes(Router $router) {
    $router->group([
        'namespace' => 'App\Http\Controllers\Frontend',
        'middleware' => 'web',
    ], function ($router) {
        require app_path('Http/Routes/frontend.php');
    });
}

现在,我想为这些命名空间/路由组设置三个不同的404页面:

Now, I want to setup three different 404 pages for these namespaces/route groups:

  • API-以JSON格式显示404响应
  • 前端-errors/404.blade.php
  • 后端-在backend/errors/404.blade.php中有一个单独的视图

如何创建这些?我一直在网上搜索,对此一无所获.

How can I create these? I have been searching the web and have come across nothing regarding this.

Laravel版本:5.2

Laravel version: 5.2

您可以通过覆盖(添加) App \ Exceptions \ Handler 中的 renderHttpException 方法来实现.该方法接收 HttpException 作为参数并返回响应.

You can achieve that by overriding (add) renderHttpException method in App\Exceptions\Handler. The method receives the HttpException as parameter and returns a response.

类似这样的东西:

protected function renderHttpException(HttpException $e) {

    $status = $e->getStatusCode();

    if (Request::ajax() || Request::wantsJson()) {
        return response()->json([], $status);
    } else if(Request::is('/backend/*')) { //Chane to your backend your !
        return response()->view("backend/errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }else {
        return response()->view("errors.{$status}", ['exception' => $e], $status, $e->getHeaders());
    }

}