Laravel5.2 How to jump to 404 when accessing a non-existent route? How to configure LNMP environment?
Laravel5.2 How to jump to 404 when accessing a non-existent route? How to configure LNMP environment?
Theoretically, if you turn off debug
, the online environment will automatically get 404
.
Do you want to "jump to page 404" or "show page 404"? If you want to jump, please configure app/Exceptions/handler.php and return a Redirect response when NotFoundException is thrown.
The Handler.php
file in the Exceptions
directory under the app
in the laravel project root directory; we can customize exceptions
and handle exceptions
here;
The most common one is
ModelNotFoundException
Here is a Demo:
<code class="php">vikin.cc/article/8</code>
<code class="PHP"> //处理Http响应异常 public function render($request, Exception $e) { switch($e){ //使用类型运算符 instanceof 判断异常(实例)是否为 ModelNotFoundException case ($e instanceof ModelNotFoundException): //进行异常处理 return $this->renderException($e); break; default: return parent::render($request, $e); } } //处理异常 protected function renderException($e) { switch ($e){ case ($e instanceof ModelNotFoundException): //自定义处理异常,此处我们返回一个404页面 return view('errors.404'); break; default: //如果异常非ModelNotFoundException,我们返回laravel默认的错误页面 return (new SymfonyDisplayer(config('app.debug'))) ->createResponse($e); } }</code>
Through the above cases, you can easily handle exceptions and give users a friendly prompt!