2012-11-25 44 views
3

我已經編寫了將所有錯誤劃分爲正常錯誤(通知,警告,...)和關鍵錯誤的錯誤處理類。將PHP錯誤轉換爲例外

現在我發現將所有錯誤轉換爲異常是一種很好的做法。這也會縮短我的代碼。

但是,我不知道如何處理這種...

  1. 是否有異常不停止腳本執行,以及例外呢?如果沒有...如何區分轉換後的錯誤?
  2. 將錯誤轉換爲異常是通過調用set_error_handler()並在那裏拋出新的ErrorException()來完成的......下一步是什麼? set_exception_handler()被自動調用?
+0

'有沒有不停止腳本執行的異常'你的意思是說錯誤而不是異常嗎? – phant0m

+0

不,我知道通過這種方式將錯誤轉換爲異常:轉換通知/警告會導致不會停止腳本的異常。轉換錯誤/致命錯誤會導致停止腳本的異常。 – khernik

回答

1
  1. Are there exceptions that don't stop scripts execution, and exceptions that do? If there aren't...how to differ converted errors?

異常不會的問題作出反應如果它們被捕獲,停止腳本執行。爲了識別轉換錯誤:

try { 
    // ... 
} catch (ErrorException $e) { 
    // converted error (probably) 
} catch (Exception $e) { 
    // another kind of exception; this basically catches all 
} 

或者:

function handle_exception(Exception $e) 
{ 
    if ($e instanceof ErrorException) { 
     // converted error (probably) 
    } else { 
     // another kind of exception 
    } 
} 
set_exception_handler('handle_exception'); 

注意ErrorException可以通過任何一段代碼被拋出,但它是爲了經常錯誤轉換隻在set_error_handler()註冊的功能。

  1. Converting errors into exception is done by calling set_error_handler() and throw new ErrorException() in there...What's next? set_exception_handler() is called automagically?

如果從你的錯誤處理程序函數拋出ErrorException沒有被捕獲其他地方在你的代碼,註冊的異常處理程序(設置使用set_exception_handler())將被調用。

2
  1. 捕獲的異常不停止你的腳本,所有未偵測到的人做
  2. 不,set_exception_handler()不會自動調用,你可以這樣做,如果你喜歡。

    後的異常已經未捕獲你set_exception_handler()設置的異常處理程序被調用,它的代碼的最後一塊腳本終止之前被調用。確保它不會導致錯誤/異常,否則會嚴重結束。

+0

@ 2它被稱爲如果你不趕它:) –

+0

@Jack不,*處理程序*被調用,而不是'set_exception_handler()'。 – phant0m

+0

我很確定這就是OP的意思:) –

1

任何未捕獲的異常都會停止執行腳本。

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

docs about this

至於set_exception_handler() - 它不是自動調用,但它是你最後的手段對所發生

Sets the default exception handler if an exception is not caught within a try/catch block. Execution will stop after the exception_handler is called.

0

請記住,只能將警告轉換爲異常,錯誤不能轉換爲異常,因爲錯誤處理程序不會運行。

set_error_handler(function ($severity, $message, $file, $line) { 
    echo 'You will never see this.' 
}); 

// Provoke an error 
function_that_does_not_exist(); 

可以使用關閉功能「捕捉」它們,但這超出了問題的範圍。