In my current project I’m querying PHP with normal HTTP-request but also via AJAX where I sometimes return JSON-formatted data and sometimes normal text. When an error occurs, in a normal request, you see the error-message and can do something about it. With AJAX-requests on the other hand you cannot be sure if you get an error or the data you want because it isn’t displayed directly — you just run into troubles because your app won’t work any more.
So I thought about an error-handling-system. My best idea is to send a 500 “Internal Server Error” header if an error occurs, so in my JS, when I send an AJAX-Request, I can simply check for errors that way and handle it.
Unfortunately PHP doesn’t send that kind of header (like when you have a parse-error, or something in your code goes wrong) natively.
Can you:
a) Tell PHP to send headers like 500 if an error occurs? Or
b) Use set_error_handler to send a 500-header and then call PHP regular error handling? Or
c) Can you, in any other way send error headers when a PHP error occurs?
i prefer using Exceptions for handling errors. First, you need to install error-to-exception error handler (http://php.net/manual/en/class.errorexception.php, example 1), then wrap your main application code in a try-catch block and send appropriate headers in the catch part. For example:
unfortunately, this doesn’t work with so-called “Fatal errors”, to handle these you have to use stupid tricks like this