2

Scenario:

Ajax calls to a PHP script. An answer is always expected in JSON Format.

Problem:

In some cases ( Exception, Error, etc.) no Json is returned but simple plain text.

Question:

How can I force PHP to always return JSON no matter what? But not turning all errors and warnings off?

I think about something like:

  • set_error_handler
  • set_exception_handler

How can I force some bad errors like parse errors to output JSON format?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Benjamin Eckstein
  • 884
  • 2
  • 9
  • 19
  • use contentType in ajax call – Sunil Pachlangia Dec 23 '15 at 12:53
  • Possible duplicate of [Clean way to throw php exception through jquery/ajax and json](http://stackoverflow.com/questions/12693423/clean-way-to-throw-php-exception-through-jquery-ajax-and-json) – Jay Blanchard Dec 23 '15 at 12:55
  • 2
    For exceptions, you could ensure you wrap all your code in try, catch blocks and make sure you output JSON if you catch anything. You should always check for errors where possible and handle them accordingly. You could take it a step further and throw exceptions if you encounter errors, which are then caught and handled within your catch blocks – Jonathon Dec 23 '15 at 12:56
  • You can use try...catch...finally blocks. More information in http://php.net/manual/en/language.exceptions.php. –  Dec 23 '15 at 13:10

1 Answers1

2

For PHP 5.x:
set_exception_handle to catch exceptions
set_error_handler to catch errors

There is no way to catch parse errors. From the docs:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT

For PHP 7.x:

All errors are catchable, so you can wrap your php script in

try {
    // your app here
} catch (Throwable $t) {
    // convert it to json
}

For any php version:

No way to handle responses sent directly from the web server, like 404, 504 to name a few.

The best thing you can do is to check response code in your javascript, and process only 200 responses, which you can perfectly control in your php script.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75