2008-08-31 3 views
11

나는 도약을하고 있습니다 : 내 PHP 스크립트는 모두 정상적으로 실패합니다! set_error_handler 작동하지 않습니다 어떻게 작동하고 싶습니다

는 적어도, 그것은 내가 (실질적으로) 시도 ... catch 문마다 한 줄을 포장하고 싶지 않아위한 ...

바라고 무엇을, 그래서 난 내 최선을 내기가 생각 내 파일의 시작 부분에 대한 사용자 정의 오류 처리기를 만듭니다.

것은 내가 연습 페이지에 그것을 테스트하고있어이 잘, 반환 작품

function customError($level,$message,$file,$line,$context) { 
    echo "Sorry, an error has occured on line $line.<br />"; 
    echo "The function that caused the error says $message.<br />"; 
    die(); 
} 

set_error_handler("customError"); 

echo($imAFakeVariable); 

:

Sorry, an error has occured on line 17. The function that caused the error says Undefined variable: imAFakeVariable.

그러나,이 설정은 정의되지 않은 기능이 작동하지 않습니다.

function customError($level,$message,$file,$line,$context) { 
    echo "Sorry, an error has occured on line $line.<br />"; 
    echo "The function that caused the error says $message.<br />"; 
    die(); 
} 

set_error_handler("customError"); 

imAFakeFunction(); 

이 반환

Fatal error: Call to undefined function: imafakefunction() in /Library/WebServer/Documents/experimental/errorhandle.php on line 17

왜 내 사용자 지정 오류 처리기가 정의되지 않은 기능을 잡기되지 않는 이유는 무엇입니까? 이로 인해 발생할 수있는 다른 문제가 있습니까?

답변

9

set_error_handler가의 코드로 오류를 처리하도록 설계되었습니다. 이는 set_error_handler사용자 오류 기능 trigger_error에 의해 발생한 오류를보고하는 방법을 의미하기 때문입니다.

그러나, 나는 당신을 도울 수있는 매뉴얼이 댓글을 발견했다 : 이러한 오류는 자동으로 예를 들어, 파일에보고해야 정말하지만

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

This is not exactly true. set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR .

<?php 

function error_handler($output) 
{ 
    $error = error_get_last(); 
    $output = ""; 
    foreach ($error as $info => $string) 
     $output .= "{$info}: {$string}\n"; 
    return $output; 
} 

ob_start('error_handler'); 

will_this_undefined_function_raise_an_error(); 

?> 

. 프로젝트에 많은 E_PARSE 오류가 없기 바랍니다. :-)

일반적인 오류보고에 관해서는 예외 사항을 고수하십시오 (내 MVC 시스템과 연동시키는 것이 도움이됩니다). 꽤 다재다능한 Exception을 구축하여 버튼을 통해 옵션을 제공하고 사용자에게 무엇이 잘못되었는지 알릴 수있는 풍부한 설명을 추가 할 수 있습니다.

1

Why isn't my custom error handler catching undefinedd functions? Are there other problems that this will cause?

짐작할 수 있듯이 정의되지 않은 함수 오류는 다른 오류 유형과 다른 실행 경로를 거친다 고 말할 수 있습니다. 아마도 PHP가 어떤 식 으로든 설계되지 않았다는 것을 제외하고는 PHP 설계자가 더 많이 말할 수 있습니다.

PHP 스타일로 작성하는 동안 스크립트가 정상적으로 작동하지 않게하려면 전체 페이지를 함수에 넣은 다음 try..catch 블록 내에서 호출하십시오. documentation 가입일

1

(강조 추가)

정의 함수 호출

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.

는 E_ERROR 트리거, 따라서 상기 에러 콜백에 의해 처리 될 수있다 (또는 그 문제에 대한 예외 핸들러에 의해). 당신이 할 수있는 일은 모두 error_reporting을 0으로 설정하는 것입니다.

추신 : 오류 처리기를 롤업하는 경우 @ 연산자를 올바르게 처리해야합니다. 문서에서 (강조는 추가) : E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE :

It is important to remember that the standard PHP error handler is completely bypassed. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

6

난 당신이 예를 들어 register_shutdown_function 또한

를 사용할 필요가 생각 : 나는 비슷한 문제에 직면 한 나는 오늘을 발견했습니다

register_shutdown_function(array($this, 'customError'));. 

    function customError() 
    { 

    $arrStrErrorInfo = error_get_last(); 

    print_r($arrStrErrorInfo); 

    } 
0

매우 흥미로운 것은. - 다음 사용하는 경우 사용자 지정 오류 처리기 기능/방법으로 오류를 잡을 것입니다 :

ini_set('display_errors', 'Off'); 
error_reporting(-1); 

set_error_handler(array("Cmd\Exception\Handler", "getError"), -1 & ~E_NOTICE & ~E_USER_NOTICE); 

에 'display_errors를'을 설정하면 여전히 잡을 핸들러로 잡을 수 '꺼짐'.

0

나는 오랫동안 오류 처리와 함께 놀았으며 대부분의 경우 작동하는 것 같습니다.

function fatalHandler() { 
    global $fatalHandlerError, $fatalHandlerTitle; 

    $fatalHandlerError = error_get_last(); 

    if($fatalHandlerError !== null) { 

     print($fatalHandlerTitle="{$fatalHandlerTitle} | ".join(" | ", $fatalHandlerError). 
       (preg_match("/memory/i", $fatalHandlerError["message"]) ? " | Mem: limit ".ini_get('memory_limit')."/peak ".round(memory_get_peak_usage(true)/(1024*1024))."M" : "")."\n". 
         "GET: ".var_export($_GET,1)."\n". 
         "POST: ".var_export($_POST,1)."\n". 
         "SESSION: ".var_export($_SESSION,1)."\n". 
         "HEADERS: ".var_export(getallheaders(),1)); 
    } 

    return $fatalHandlerTitle; 
} 

function fatalHandlerInit($title="phpError") { 
    global $fatalHandlerError, $fatalHandlerTitle; 

    $fatalHandlerTitle = $title; 
    $fatalHandlerError = error_get_last(); 

    set_error_handler("fatalHandler"); 
} 

이제 메모리가 고갈되면 매번보고하지 않는 문제가 있습니다. 그것은 얼마나 많은 메모리가 사용되는지에 달려 있다고 생각됩니다. 무한 루프에서 큰 파일을로드하는 스크립트를 작성했습니다 (~ 6.6M의 메모리가 필요함). 카메라 설정 :

ini_set('memory_limit', '296M'); 

fatalHandlerInit("testing"); 

$file[] = file("large file"); // copy paste a bunch of times 

이 경우 나는 보고서로 오류를 얻을 수 있으며 45 파일로드에 죽는다.

Setup2 - 동일하지만 변경 : ini_set ('memory_limit', '299M');

이번에는 오류가 발생하지 않으며 사용자 정의 오류 기능을 호출하지도 않습니다. 스크립트는 같은 줄에서 죽습니다.

단서가있는 이유는 무엇입니까?

관련 문제