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

  1. Create a new yii2-app-basic application by using the Composer package manager, as described in the official guide at http://www.yiiframework.com/doc-2.0/guide-start-installation.html.
  2. Add the fail action to your SiteController:
    class SiteController extends Controller
    {
        // …
    
        public function actionFail()
        {
            throw new ServerErrorHttpException('Error message example.');
        }
    }
  3. Add the web/.htaccess file with the following content: ...

Get Yii2 Application Development Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.