我正在努力尝试深入了解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视图,但是我不知道怎么做?
答案 0 :(得分:2)
找不到页面时,它将抛出NotFoundHttpException
,
存在中止方法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
内有一个处理程序
内部Handler.php
: renderHttpException 方法用于根据Exception的状态代码呈现视图。
like:
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);
}
答案 1 :(得分:0)
Laravel提供了默认的exception handler App\Exceptions\Handler
,它实现了一种render
方法,该方法将异常转换为HTTP响应。
Http/Kernel.php
在try catch块中调用异常处理程序。 See here。