views:

187

answers:

1

Normally when an exception is thrown, Error controller takes command and displays error page with regular common header and footer.

This behavior is not wanted in Ajax request. Because in case of error, whole html page is sent over. And in cases where I'm directly loading the content of http response in a div, this is even more unwanted.

Instead in case of Ajax request, I just want to receive 'the actual error' thrown by exception.

How can I do this?

I think, one dirty way could be: set a var in ajax request and process accordingly. Not a good solution.

+1  A: 

if you use either the contextSwitch or ajaxContext action helpers to encode your error (possibly turning off autoJsonSerialization) you could just pass the errors back as JSON / XML objects.

http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.contextswitch

class Error_Controller extends Zend_Controller{
    public function errorAction(){
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext($this->getRequest()->getActionName(),'json')
            ->initContext();
        $errors = $this->_getParam('error_handler');
        $this->view->exception = $errors->exception;
    }
}

From there you have to either pass a format=json parameter which each AJAX request or setup a routing chain that automatically appends it.

For a 'slightly' more secure setup you could use ajaxContext as your helper and only requests that have the XMLHttpRequest header will be served json.

Ballsacian1
@Ballsacian1: Could you please provide a code snippet for JSON? That'd be really helpful. Thanks.
understack