Displaying custom errors
In Yii, the error handling is very flexible, so you can create your own error handler for errors of a specific type. In this recipe, we will handle a 404 not found error in a smart way. We will show a custom 404 page that will suggest the content based on what was entered in the address bar.
Getting ready
- Create a new
yii2-app-basicapplication by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html. - Add the fail action to your
SiteController:class SiteController extends Controller { // … public function actionFail() { throw new ServerErrorHttpException('Error message example.'); } } - Add the
web/.htaccessfile with the following content:RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php - Configure pretty URLs for the
urlManagercomponent in yourconfig/web.phpfile:'components...