Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper mechanism for sending PHP errors to the client

Greetings,
I was trying to discover a proper way to send captured errors or business logic exceptions to the client in an Ajax-PHP system. In my case, the browser needs to react differently depending on whether a request was successful or not. However in all the examples I've found, only a simple string is reported back to the browser in both cases. Eg:

if (something worked)
    echo "Success!";
else
    echo "ERROR: that failed";

So when the browser gets back the Ajax response, the only way to know if an error occurred would be to parse the string (looking for 'error' perhaps). This seems clunky.

Is there a better/proper way to send back the Ajax response & notify the browser of an error?
Thank you.

like image 560
Chris Z Avatar asked Apr 07 '10 14:04

Chris Z


2 Answers

You could send back an HTTP status code of 500 (Internal server error) , and then include the error message in the body. Your client AJAX library should then handle it as an error (and call an appropriate callback etc.) without you having to look for strings in the response.

like image 129
Tom Haigh Avatar answered Oct 14 '22 09:10

Tom Haigh


I generally send back a JSON response like this:

$response = array('status' => 'error', 'message' => 'an unknown error occured');

if( some_process() ) {
    $response['status'] = 'success';
    $response['message'] = 'Everything went better than expected.';
} else {
    $response['message'] = "Couldn't reticulate splines.";
}

die( json_encode($response) );

So, I can check the status of response.status in my JavaScript and look for a value of "sucess" or "error" and display response.message appropriately.

like image 20
Annika Backstrom Avatar answered Oct 14 '22 10:10

Annika Backstrom