Originally Posted by
adrive
hi, im not entirely fluent in the http headers, but i just did a test,
with an ajax page that calls php to save something. I then tried throwing an exception from php, but ajax's status is still 200.
So does this mean i have to return other http status code manually incase i catch an exception?
Do you mean exceptions like: a try, catch block and throw in PHP5?
XHR object reflects the HTTP Request and Response in the HTTP protocol. Since PHP5 exceptions are only on the PHP code level, they are not seen as an exception by XHR.
Only HTTP Response Codes are reflected in the XHR object.
What you can do is depending on the format of your HTTP Response, let the client know that an exception was encountered.
For this you need a more structured format than just plain text, maybe JSON or XML. XHR understands XML natively and thus will parse it out into a DOM Object that you can work with. JavaScript can parse JSON with a simple eval().
For example w/ XML:
<?php
// example exception handling for XHR in XML
// set content-type as xml
header('Content-Type: text/xml');
// PHP 5
try {
doSomething();
} catch (Exception $e) {
// handle either error here
echo '<reponse>';
echo '<exception msg="'.$e->getMessage().'" />';
echo '</response>';
exit();
}
?>
For example w/ JSON:
<?php
// example exception handling for XHR in JSON format
// set content-type as javascript
header('Content-Type: text/javascript');
// PHP 5
try {
doSomething();
} catch (Exception $e) {
// handle either error here
echo '{exception: {msg:\''.$e->getMessage().'\'}}';
exit();
}
?>
Then on your client side:
If you use XML, get the XHR.responseXML DOM object after the XHR response is received. Traverse the DOM tree for the exception node and get its message attribute value.
If you use JSON for example, just eval("(".XHR.responsetext.")"); saving it to a variable and get the exception property.
You could also have PHP modify the HTTP Response to reflect an exception occurring in the PHP code. Then you can test for exceptions in the XHR Object directly.
Note: The HTTP Response is just plain text. XHR will only parse out the HTTP headers and body into the XHR properties. It cannot understand an exception in any server side language. You have to code this into your Client.