我正在开发一个由ajax请求调用的php脚本,并且应该回显一些要解析的响应代码。
例如:
die('#1:200|Success|'.$data);
或者另一个:
die('#0:100|Access Denied|');
现在,我还想包括在脚本执行期间可能发生的任何错误或警告 - BUT 附加到消息末尾。
那么,将所有错误捕获到某个变量中的优雅方法是什么?
编辑
好吧,要理解它的含义并不容易,手册在很多事情上都不清楚。
但是好吧,我会尝试举例说明我是如何理解它的,然后如果我弄错了,请指出它:-)
//So guess first I off error reporting that would naturally occur.
error_reporting(0);
//Then I will define array to stuff the errors in.
$errors=array();
//Then I make my handler function.
function handler($errno,$errstr){
global $errors;
$errors[]=$errno.': '.$errstr; //Stuff it into array.
}
//Then I define handler.
set_error_handler('handler',E_ALL);
这是正确的用法吗?
它还说:
The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.
还有一个问题,为什么它不能捕获严格的错误?
我总是需要它在 ajaxing 时捕获错误:
header('content-type: application/json; charset=utf-8');
error_reporting(E_ALL);ob_start();
function error($msg,$do = false)
{
//personal error message
if(!isset($_SESSION))session_start();
trigger_error($msg."'n".(isset($_SESSION)?"[".$_SESSION['id']."|".$_SESSION['name']."]":"")."-----------");
ob_clean();
die(json_encode(array($msg,$do)));
}
function ob_error($msg = "Error!",$do = "ob_error")
{
if($s = ob_get_clean())
error("$msg'nDetails:'n$s",$do);
}
用法:
//require the php above
//do something
//call error("acces denied") if there is an fatal error
//do anything else
//call ob_error() at the end: if there was anything outputted like warning/notice it will shown
//call die(json_encode(array(1, ...anything you need*...))); - this will run only if there was nothing displayed
客户端站点使用情况:
$.post('/_ajax/... .php',{
'param1':...
},function(a){
if(a[0]=="1") //OK
{
//* do something with a[n]
}else{ //onError
alert(a[0]);
//what to do client site after the error
if(a[1]=="refresh")
location.href=location.href;
}
},"json").error(function() {alert("postError"));