I am writing a CakePHP (cakephp.org) controller. One of the actions, "myAction", responds to AJAX requests. I find it annoying that if anything goes wrong in the action handler, Cake always responds with an error page and an HTTP status of 200, meaning that it fails silently, so I have to open a new window and run the AJAX request directly from the address bar to see the output and find out what went wrong. As an example, say I write the following action that produces a divide-by-zero error
function myAction() {
0/0; // produce a divide-by-0 error for the sake of example
}
Cake returns an error page as its response with a HTTP status code of 200. (In other words, Cake is telling me it returned a "successful" error page!)
I tried adding the following two lines before the divide-by-zero:
define('DISABLE_DEFAULT_ERROR_HANDLING', true);
set_error_handler('myError', E_ALL);
0/0;
then in the global namespace:
function myError($code, $msg) {
CakeLog::write('error', "code=$code: $msg");
header('HTTP/1.0 500 Internal Error');
die($code);
}
In this case, CakePhp never sends a response. To the browser, the response is left "pending" forever.
For comparison, I wrote a simple standalone (PHP, no Cake) page:
<?php
function myHandler($errrno, $msg) {
header('HTTP/1.0 500 Internal Error');
die($msg);
}
set_error_handler(myHandler, E_ALL);
0/0;
die('got here');
?>
It's output is
Division by zero
as expected.
I know that there must be a better way to configure CakePHP automatically handle errors in controller/action handlers that don't require a massive code undertaking.
The excellent posts on CakePHP and jQuery - Unobtrusive actions and Using HTTP status codes to reflect success/failure of Web service request? are helpful for letting me know I'm on the right track but they still don't satisfy my desire to make Cake return an HTTP response of 50x when some unexpected exception occurs. Then, when the response comes back, the browser could display a message on the page like, "An error occured, notify the webmaster" and I would know to look in the Apache error-log to find out what really happened.
All ideas are welcome.