lardlad
lardlad

Reputation: 99

Send PHP errors through JSON

I am trying to debug a page that sends emails with attachments via ajax and when PHP kicks out an error, I get "Parse Error" because the error is not being sent back via JSON. Is there anyway to wrap up the PHP errors so I can alert them and see exactly what PHP errors are coming up?

What I am hoping to see in the js alert is the same thing you would see printed on the screen if this form was not submitted using ajax.

Upvotes: 0

Views: 3149

Answers (4)

yPhil
yPhil

Reputation: 8357

function json_error($msg) {
    header('HTTP/1.1 500 ' . $msg);
    die(json_encode(array('error' => $msg)));
}

json_error('something bad happened');

This will trigger the error: ajax callback on the JS side.

echo json_encode(array('anything' => 'really', 'any key' => 'any value'));

Will trigger the success: callback.

Upvotes: 1

CodeZombie
CodeZombie

Reputation: 5377

Use HTTP status codes. Simple and clean.

On the client side: You can handle the HTTP states with the success and failure callbacks of the common JavaScript frameworks.

On the server side: Use exceptions and handle them with a catch block. In the catch block set the HTTP status code and echo the exception message. Or use the less fancy set_error_handler() function and set the status code and error message in the callback function.

Upvotes: 5

zrvan
zrvan

Reputation: 7743

You'd use exception-handling, look here: http://www.php.net/manual/en/language.exceptions.php

Upvotes: 0

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

Fatal errors usually can't be handled *.

Try improving your code and just don't make parse errors or other fatal errors. Handling warnings and notices is easy: http://php.net/manual/en/function.set-error-handler.php

*: It's possible but it takes a lot of effort.

Upvotes: 0

Related Questions