I'm using CodeIgniter to host a RESTful API and I'd like to capture any API response that does not return an expected status code. This is probably most easily explained with an example. In general, my code looks like this:
function post_comment()
{
$comment = $_POST['comment'];
$result = do_something_with_comment($comment);
if ($result === true)
{
return_json_response(200, 'OK!');
}
else
{
return_json_response(400, 'Something terrible happened...');
}
}
Returning either a 200 or 400 is perfectly valid. My problem is: how to capture errors when do_something_with_comment() has a fatal error, or if I leave a print debug inside of do_something_with_comment(). In the former case, I'll never reach return_json_response(). In the latter case, I'll reach it, but the screen debug will corrupt the JSON response.
Is there any way to create a generic wrapper around this to capture any unexpected output or termination?
There's a function register_shutdown_function() within which you can set your own closing handler for every script. Just do what you need there.
BTW: Make your scripts as bullet-proof as you can. Your scripts shouldn't ever have fatal errors, segfaults, or such runtime errors. Any response, even invalid for client is valid in context of request handling. I'd encourage you to take a look at Symfony2 framework or simply at its HttpKernel / HttpFoundation components as they quite nicely wrap this process in a friendly interface.
In general you could:
Use exception /exception handling as much as possible
Register a custom errorhandler that transforms PHP errors into exceptions, for instance put this in top of your config/config.php
Register an uncaught exception handler, put something like this in your config/config.php
EDIT
Set a termination handler:
Set a custom assert handler that converts asserts into exceptions, put something like this in your config/config.php:
Then, and this is your answer, use wrappers like this in your controllers
You can tune and customize the whole thing to your likings!
Hope this helps.
EDIT
You will also need to intercept the CI show_error method. Place this in application/core/MY_exceptions.php:
And leave in application/config/database.php this setting on FALSE to have database errors converted into exceptions.
CI has a few (very) weak points, such as exception-handling but this will go a long way correcting that.