4

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.
}
?>
3
  • I would echo Maarten's answer - the best way to prevent errors and warnings from PHP is to track down what's causing them, rather than look for ways to get around them. Commented Mar 5, 2017 at 0:45
  • I agree. The point is, I am already checking for (all) errors. It's like with exceptions: once you use try/catch to handle them, you don't want the default exception behavior to occur (e.g. you want your own error message shown properly in your own app). I can catch exceptions, but there is not try/catch for php warnings and notices (is there?), so even if I check all results and proceed accordingly, php still issues them and breaks the app. Commented Mar 5, 2017 at 10:09
  • What is the JSON data that's getting returned? How about we look for what's generating this unexpected whitespace character then? :) Commented Mar 5, 2017 at 14:25

1 Answer 1

2

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'.

Sign up to request clarification or add additional context in comments.

4 Comments

This is what I am doing, though: writing error handlers, and, here, introducing errors on purpose to test them: $db = new SQLite3( 'bad.db', SQLITE3_OPEN_READONLY ); - this throws an exception on failure, which I can catch. But: $result = $db->querySingle( 'SELECT [badcolumn] FROM [badtable] etc...' ); - here, if the query is invalid, two things happen: $result is empty, and PHP issues a warning. I do not want that warning, since I am checking the result (and can ask sqlite3 for lastErrorCode). I'm new to php, so I needed to hear it's ok to suppress this verbosity here :-)
in that case disable warnings. see php.net/manual/en/function.error-reporting.php or dont display them by ini_set('display_errors',0) see stackoverflow.com/questions/9729000/…
An example: using php to dig out EXIF data. Users supply images, the app has no control over quality of EXIF data. Code reading that data throws warnings for some EXIF params. I wish the app to know about those so the app can inform the user ... but if E_WARNINGS is set to OFF, not possible and if set to ON, I get the same endless headache with JSON. Advising people to build their apps so features of the language are not useable, seems like a strange thing. I note this post is as of Dec. '19 2.5 yrs aged. Has anyone devised, and shared a workaround for that nonsense of php stomping JSON?
What I wound up doing is after images are uploaded, run the check for the EXIF params in a seperate php and log the warnings / errors, then seperately let the users know if they need to send a repaired image or offer to repair the EXIF data for them. Kludgy and a whole lot more coding but it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.