1

私はajaxリクエストによって呼び出され、解析される応答コードをエコーすることになっているphpスクリプトに取り組んでいます。

例えば:

die('#1:200|Success|'.$data);

または別のもの:

die('#0:100|Access Denied|');

ここで、スクリプトの実行中に発生した可能性のあるエラーや警告も含めたいと思いますが、メッセージの最後に追加されています。

では、すべてのエラーをいくつかの変数に取り込むためのエレガントな方法は何でしょうか?

編集

さて、それがどのように使用されるのかを理解するのは簡単ではありません、マニュアルは多くのことについて明確ではありません。

しかし、わかりました、私はそれをどのように理解するかの例を作ろうとします、そして私がそれを間違えているならそれを指摘してください:-)

//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.

また、なぜ厳密なエラーをキャプチャしないのかという質問もあります。

4

1 に答える 1

1

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"));
于 2012-08-13T13:34:19.820 に答える