I have a php script which reads a record from a database and returns a json object. I have error handling in the script, so that if an exception is thrown or other errors occur, I still return a well-formed json response (with an error code and all). This works.
However: if PHP feels it has something to say, it still says it after it sends the json response. This breaks the json parser on the client side. So instead of the ajax call succeeding and displaying an error message such as "database file not found", the call fails with a json parser error, which is not helpful (since it overrides the original, preserved error information):
SyntaxError: JSON.parse: unexpected non-whitespace character
after JSON data at line 1 column 120 of the JSON data
I can suppress PHP's messages with error_reporting(0) - but is there a better way? The code (outline) follows:
<?php
header('Content-type: application/json');
const RESP_OK = 0;
const RESP_EXCEPTION = 1;
try {
// do the database stuff and build $response
$response['exitcode'] = RESP_OK;
} catch ( Exception $e ) {
// put error info in the response
$response['exitcode'] = RESP_EXCEPTION;
$response['error'] = 'code: ' . $e->getCode() . ' (line ' .
$e->getLine() . ') message: ' . $e->getMessage();
} finally {
// always send back a response
echo json_encode( $response );
error_reporting(0);
// also close the db here etc.
}
?>