【问题标题】:How does Laravel create a 404 view when a route is not defined未定义路由时 Laravel 如何创建 404 视图
【发布时间】:2019-10-19 22:20:31
【问题描述】:

我正在努力了解 Laravel 的底层,因为这有助于我学习和记住某些东西是如何工作的。我无法弄清楚基本的 404 是如何工作的。

我在 157 的 Illuminate\RoutingRouteCollection.php 中尝试了很多 var_dumping

public function match(Request $request)
{
    $routes = $this->get($request->getMethod());

    // First, we will see if we can find a matching route for this current request
    // method. If we can, great, we can just return it so that it can be called
    // by the consumer. Otherwise we will check for routes with another verb.
    $route = $this->matchAgainstRoutes($routes, $request);

    if (! is_null($route)) {
        return $route->bind($request);
    }

    // If no route was found we will now check if a matching route is specified by
    // another HTTP verb. If it is we will need to throw a MethodNotAllowed and
    // inform the user agent of which HTTP verb it should use for this route.
    $others = $this->checkForAlternateVerbs($request);

    if (count($others) > 0) {
        return $this->getRouteForMethods($request, $others);
    }


    throw new NotFoundHttpException;
}

看起来一定是 NotFoundHttpException,输出 404 视图,但我不知道怎么做?

【问题讨论】:

    标签: laravel laravel-5 laravel-blade


    【解决方案1】:

    找不到页面时会抛出NotFoundHttpException

    abort方法vendor/laravel/framework/src/Illuminate/Foundation

    public function abort($code, $message = '', array $headers = [])
    {
        if ($code == 404) {
            throw new NotFoundHttpException($message);
        }
    
        throw new HttpException($code, $message, null, $headers);
    }
    

    laravel 为错误代码提供了不同的视图:在Exceptions/views 内部有可供查看的视图

    401,403,404,419,429,500,503
    

    现在Illuminate\Foundation\Exceptions内部有一个处理程序

    inside Handler.php :renderHttpException 方法用于根据 Exception 的状态码渲染视图。

    喜欢:

    1) renderHttpException:此方法检查是否存在给定状态码的视图,然后返回视图。

    /**
         * Render the given HttpException.
         *
         * @param  \Symfony\Component\HttpKernel\Exception\HttpException  $e
         * @return \Symfony\Component\HttpFoundation\Response
         */
        protected function renderHttpException(HttpException $e)
        {
            $this->registerErrorViewPaths();
    
            if (view()->exists($view = "errors::{$e->getStatusCode()}")) {
                return response()->view($view, [
                    'errors' => new ViewErrorBag,
                    'exception' => $e,
                ], $e->getStatusCode(), $e->getHeaders());
            }
    
            return $this->convertExceptionToResponse($e);
        }
    

    2) registerErrorViewPaths : 该方法将注册错误视图的路径

     /**
         * Register the error template hint paths.
         *
         * @return void
         */
        protected function registerErrorViewPaths()
        {
            $paths = collect(config('view.paths'));
    
            View::replaceNamespace('errors', $paths->map(function ($path) {
                return "{$path}/errors";
            })->push(__DIR__.'/views')->all());
        }
    

    现在,如果您想制作自定义 404 页面并想要渲染它:

    app/Exceptions/Handler.php

     public function render($request, Exception $exception)
     {
            if($this->isHttpException($exception)){
                switch ($exception->getStatusCode()) {
    
                    case 404:
                        return view('path-to-custom404-here');
                        break;
    
                }
            }
            return parent::render($request, $exception);
    }
    

    【讨论】:

      【解决方案2】:

      Laravel 提供了一个默认的exception handlerApp\Exceptions\Handler,它实现了一个render 方法,就是将异常转化为HTTP 响应的方式。

      异常处理程序由 Http/Kernel.php 在 try catch 块中调用。 See here.

      【讨论】:

        猜你喜欢
        • 2018-06-28
        • 2015-08-20
        • 2020-05-22
        • 2019-01-15
        • 1970-01-01
        • 2019-12-01
        • 2018-06-30
        • 2018-12-16
        相关资源
        最近更新 更多