Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

329
Views
Prevent PHP warnings and errors from breaking json parser?

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.
}
?>
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!