PHP Exception Handling with JQuery
I am using JQuery to call a PHP function that returns a JSON string on success or throws some exceptions. I am currently calling jQuery.parseJSON()
in a response and if it fails, I assume the response contains an exception string.
$ .ajax ({
type: "POST",
url: "something.php",
success: function (response) {
try {
var json = jQuery.parseJSON (response);
}
catch (e) {
alert (response);
return -1;
}
// ... do stuff with json
}
Can anyone suggest a more elegant way to catch the exception?
Thanks a lot, Itamar
a source to share
Well, you can have a global exception handler in PHP that will call json_encode
on it and then iterate over it.
<?php
function handleException( $e ) {
echo json_encode( $e );
}
set_exception_handler( 'handleException' );
?>
Then you can check if, say json.Exception != undefined
.
$.ajax({
type: "POST",
url: "something.php",
success: function(response){
var json = jQuery.parseJSON( response );
if( json.Exception != undefined ) {
//handle exception...
}
// ... do stuff with json
}
a source to share
Catch the exception in your PHP script - using a block try .... catch
- and when an exception occurs, have the script output a JSON object with an error message:
try
{
// do what you have to do
}
catch (Exception $e)
{
echo json_encode("error" => "Exception occurred: ".$e->getMessage());
}
you should look for the error message in the jQuery script and possibly print it.
Another option is to send a header 500 internal server error
when PHP encounters an exception:
try
{
// do what you have to do
}
catch (Exception $e)
{
header("HTTP/1.1 500 Internal Server Error");
echo "Exception occurred: ".$e->getMessage(); // the response body
// to parse in Ajax
die();
}
your Ajax object will then call the error callback and you will do your error handling there.
a source to share