"clean way to throw php exception through jquery/ajax and json" Answer’s


You could do something like this in PHP (assuming this gets called via AJAX):


try {
    if (some_bad_condition) {
        throw new Exception('Test error', 123);
    echo json_encode(array(
        'result' => 'vanilla!',
} catch (Exception $e) {
    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage(),
            'code' => $e->getCode(),

In JavaScript:

    // ...
    success: function(data) {
        if (data.error) {
            // handle the error
            throw data.error.msg;

You can also trigger the error: handler of $.ajax() by returning a 400 (for example) header:

header('HTTP/1.0 400 Bad error');

Or use Status: if you're on FastCGI. Note that the error: handler doesn't receive the error details; to accomplish that you have to override how $.ajax() works :)

Wednesday, March 31, 2021
answered 10 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :