How to create a custom exception and show it friendly with CJuiDialog

  1. Step 1 - Create a custom exception class
  2. Step 2 - Create a translation's file
  3. Step 3 - Create a custom handler
  4. Step 4 - Configure the "onException" parameter.
  5. Step 5 - Change your template's view
  6. Last Step - Call the custom exception
  7. Result
  8. Links

Sometimes we need to create our custom exception and show it to the end user through a friendly way . In this article, I'm showing how to do it using CJuidialog.

Step 1 - Create a custom exception class

Create a class named 'FriendlyException' and put it in the folder "components". There is a constant to get the custom message in the translation's file (see below) and a constructor method.

<?php

/**
 * Description of FriendlyException
 *
 * @author fosales
 */
class FriendlyException extends CException {
    const EXC_EXAMPLE_ONE = 1;
    
    function __construct($code, $paramsMessage = array()) {
        parent::__construct(Yii::t('exception', $code, $paramsMessage), $code);

    }    
    
}

Step 2 - Create a translation's file

Create a file named "exception.php" and put it in the folder "messages/en". Do not forget to set "language" parameter value to "en" in config/main.php.

<?php

return array(
    FriendlyException::EXC_EXAMPLE_ONE => 'This is the example number one with parameter {parameter}.',
);

Step 3 - Create a custom handler

Create a class named 'FriendlyHandler'. The class only handles exceptions of the type FriendlyException.

<?php

/**
 * Description of FriendlyHandler
 *
 * @author fosales
 */
class FriendlyHandler {

    public static function handle(CExceptionEvent $event) {
        if ($event->exception instanceof FriendlyException && !Yii::app()->getRequest()->getIsAjaxRequest()) {
            //the id differentiates dialog messages from the flash messages
            $id = rand(1, 999999);
            Yii::app()->user->setflash($id, array('title' => $event->exception->getCode(), 'content' => $event->exception->getMessage()));

            $event->handled = true;
            //redirect to the controller that generated exception
            $controller = new CController('friendlyHandlerController');
            $controller->redirect(Yii::app()->request->urlReferrer);
        }
    }
}

Step 4 - Configure the "onException" parameter.

In the file "config/main.php", set the "onException" value telling the class and method that will handle the custom exception.

<?php

// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');

// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
	'name'=>'My Web Application',

	// preloading 'log' component
	'preload'=>array('log'),

	// autoloading model and component classes
	'import'=>array(
		'application.models.*',
		'application.components.*',
	),

      'onException' => array('FriendlyHandler', 'handle'),
    
        /**/


  

Step 5 - Change your template's view

Configure your "views/layout/main.php" file to show the flash messages like dialog messages. Put the code below in some place after body tag or render it in a partial view.

<?php
$flashMessages = Yii::app()->user->getFlashes();
if ($flashMessages) {     
    foreach ($flashMessages as $key => $message) {
        //numeric value generated by friendly handler
        if (is_numeric($key)) {
            $this->beginWidget('zii.widgets.jui.CJuiDialog', array(
                'id' => $key,
                'options' => array(
                    'modal' => 'true',
                    'title' => $message['title'],
                    'autoOpen' => true,
                ),
            ));

            printf('<span class="dialog">%s</span>', $message['content']);

            $this->endWidget('zii.widgets.jui.CJuiDialog');
        }
    }
}
?>

Last Step - Call the custom exception

Throws the custom exception.

public function actionContact() {

        throw new FriendlyException(FriendlyException::EXC_EXAMPLE_ONE, array('{parameter}' => 'Lets rock ;)'));

        /**
         * ...
         */
    }

Result

Result

Links

Related information

0 0
2 followers
Viewed: 11 513 times
Version: 1.1
Category: How-tos
Written by: Fábio Sales
Last updated by: Fábio Sales
Created on: Jan 31, 2015
Last updated: 3 years ago
Update Article

Revisions

View all history

Related Articles