If you type a URL like http://site.com/blog/blogblogyjr , where blogblogyir is a non-existent page of site.com/blog, instead of page 404 this appears: image

The NotFoundHttpException file itself is located: D: \ sites \ site \ yii2 \ vendor \ yiisoft \ yii2 \ web

code from BlogController.php (located in dir: D: \ sites \ site \ yii2 \ frontend \ controllers)

<?php namespace frontend\controllers; use common\models\Blog; use Yii; use yii\web\Controller; /** * Blog controller */ class BlogController extends Controller { /** * Displays homepage. * * @return mixed */ public function actionIndex() { #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_DESC])->all(); $blogs = Blog::find()->andWhere(['status_id'=>1])->orderBy('sort')->all(); #$blogs = Blog::find()->where(['status_id'=>1])->orderBy(['id' => SORT_ASC])->all(); return $this->render('all',['blogs'=>$blogs]); } public function actionOne($url) { if($blog = Blog::find()->andWhere(['url'=>$url])->one()) { return $this->render('one',['blog'=>$blog]); } throw new NotFoundHttpException (); } } 

an instruction in BlogController helped - use yii \ web \ NotFoundHttpException; but how to make a post in BlogController throw earn new NotFoundHttpException ('oops, there is no such blog'); Now it just shows Not Found (# 404) page not found

  • one
    You must connect the namespace where NotFoundHttpException lies or call it directly yii \ web \ NotFoundHttpException also in the config you need to configure errorHandler - Adobe
  • Help Notice in BlogController helped - use NotFoundHttpException; Method 2 is not completely clear: ErrorHandler is in the same folder as NotFoundHttpException -D: \ sites \ site \ yii2 \ vendor \ yiisoft \ yii2 \ web how can I configure it and call it directly? - Fin
  • Folder and namespace are not the same. There is a PSR, according to which it is recommended that addressing of namespaces and directories should be made the same where the class itself lies. Learn more about how Namespace works in PHP - Adobe

2 answers 2

frontend/config/local-web.php (some such)

 ... 'errorHandler' => [ 'errorRoute' => 'site/error', ... ], ... 

frontend/views/site/error.php

 <?php echo 'custom template'; ?> 

Where the default template for the cut is - I probably will not tell you.

    You can specify an action in which errors will be processed:

     ... 'errorHandler' => [ 'errorAction' => 'site/error', ], ... 

    And in the controller SiteController add something like this:

     public function actionError() { $exception = Yii::$app->errorHandler->exception; if ($exception !== null) { if ($exception->statusCode == 404) return $this->render('error404', ['exception' => $exception]); else return $this->render('error', ['exception' => $exception]); } } 

    Create an error404 view and display everything you want there.

    Link to documentation: https://nix-tips.ru/yii2-api-guides/guide-ru-runtime-handling-errors.html