Home > Backend Development > PHP Tutorial > laravel access non-existent route jump problem!

laravel access non-existent route jump problem!

WBOY
Release: 2023-03-02 13:02:01
Original
1652 people have browsed it

Laravel5.2 How to jump to 404 when accessing a non-existent route? How to configure LNMP environment?

Reply content:

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.

1. If you just want to throw a 404 error, the debug switch can satisfy you;


2. If you want to handle exceptions or customize exceptions, please refer to the following;

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:

route:

<code class="php">vikin.cc/article/8</code>
Copy after login

Handler file:

<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>
Copy after login

Through the above cases, you can easily handle exceptions and give users a friendly prompt!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template