Display a nice exception message on ajax requests

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

  1. Basics
  2. But
  3. Example

Basics

When an exception is thrown in our code like

throw new CHttpException(403, 'You are not authorized to perform this action.');

if it is a CHttpException or if YII_DEBUG is not true, the error message can be displayed by using CErrorHandler::errorAction. In the default code generated by yiic this is set to SiteController::actionError() by this settings in config/main.php

'errorHandler' => array(
    'errorAction' => 'site/error',
),

But

in Yii versions previous to 1.1.9 exceptions was handled differently during ajax request and displayed by CApplication::displayException(). This way the exception message displayed on ajax requests could not be customized. The message for the CGridView delete request with YII_DEBUG set to true looked like old exception message on ajax request

In Yii version 1.1.9 the check for ajax request has been removed so now the exception message is handled by CErrorHandler::errorAction even during ajax requests.

This way the message can be customized for ajax requests.

Example

by using this code

public function actionError()
{
    if($error=Yii::app()->errorHandler->error)
    {
    	if(Yii::app()->request->isAjaxRequest)
    		echo $error['message'];
    	else
        	$this->render('error', $error);
    }
}

the exception message for CGridView delete request will look like new exception message on ajax request

12 0
19 followers
Viewed: 40 931 times
Version: Unknown (update)
Category: Tips
Last updated by: Maurizio Domba Cerin
Created on: Aug 29, 2011
Last updated: 6 years ago
Update Article

Revisions

View all history

Related Articles