Clean way to throw php exception through jquery/ajax and json

前端 未结 5 742
孤城傲影
孤城傲影 2020-12-04 18:02

Is there a clean, easy way to throw php exceptions through a json response jquery/ajax call.

5条回答
  •  北海茫月
    2020-12-04 18:39

    As a complement to the previous answers, instead of repeating the same code for json encoding in all your exceptions, you could set an exception handler to be used only in the needed scripts. For instance:

    function ajaxExceptionHandler($e) {
        echo json_encode(array(
            'error' => array(
            'code' => $e->getCode(),
            'msg' => $e->getMessage())
        ));
    }
    

    Then, in your ajax handler,

    set_exception_handler('ajaxExceptionHandler');
    

提交回复
热议问题