paul smith paul smith - 2 months ago 14
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;

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?


You can use CakeExceptions as explained in the Cookbook: 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:

    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:

    // Output for AJAX calls
    echo $name;

    //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.'); ?>
    if (Configure::read('debug') > 0 ):
        echo $this->element('exception_stack_trace');

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!