Reputation: 7316
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.
}
?>
Upvotes: 4
Views: 1909
Reputation: 1721
Error reporting is a debug feature, hence it could/should/would be turned off in a production environment, not in your development.
You should write you code in such a way that all is covered by your code.
Analyse every error and warning and see now this can be handled in such a way that 'PHP does not feel it has something to say'.
Upvotes: 2