paul smith paul smith - 3 months ago 31
PHP Question

Ajax error handling in CakePHP

I want to do something very similar to this but in the CakePHP world for AJAX requests. At the moment I am doing this:

$this->autoRender = false;
$this->response->statusCode(500);


It is based off of this. However this solution does not allow me to include a custom message like in the Rails example, so that way, in my clients side error handler, I can display the message included in the 500 error response.

How would I implement the same functionality in CakePHP like the Ruby on Rails example?

Answer

You can use CakeExceptions as explained in the Cookbook: http://book.cakephp.org/2.0/en/development/exceptions.html BUT if you want to use your custom messages I found no other way than using debug = 1 in your production mode :(

Here's my approach with built in methods:

In your controller:

if($this->request->is('ajax')){
    Configure::write('debug', 1);
}

if(!$allowed) {
    throw new InternalErrorException('Keep your fingers away from me!'); // 500 error
}

Change the error template to output nothing but the error when used in AJAX calls in /app/View/Errors/error500.ctp:

<?php
if($this->request->is('ajax')):
    // Output for AJAX calls
    echo $name;

else:
    //Standard CakePHP output ?>
    <h2><?php echo $name; ?></h2>
    <p class="error">
        <strong><?php echo __d('cake', 'Error'); ?>: </strong>
        <?php echo __d('cake', 'An Internal Error Has Occurred.'); ?>
    </p>
    <?php
    if (Configure::read('debug') > 0 ):
        echo $this->element('exception_stack_trace');
    endif;

endif; ?>

You can then parse the returned text in your AJAX. Here's the jQuery parts I use:

//...
error: function (request) {
    yourErrorShowingFunction(_this, request.responseText);
}
//...

Hope this helps :)

If anyone has an idea how to use the custom errors in production mode (without overwriting the debug mode) I would be very happy!

Comments