問題描述
我熟悉一些基礎知識,但我想了解更多關于何時以及為什么應該在 PHP 中使用錯誤處理(包括拋出異常),尤其是在實時站點或 Web 應用程序中.它是否可以被過度使用,如果是,過度使用是什么樣的?是否有不應該使用的情況?另外,在錯誤處理方面有哪些常見的安全問題?
I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be used? Also, what are some of the common security concerns in regard to error handling?
推薦答案
要補充已經說過的一件事是,將 Web 應用程序中的任何錯誤記錄到日志中是最重要的.這樣,正如 Jeff Coding Horror" Atwood 所建議的那樣,當您的用戶在使用您的應用程序時遇到問題時,您就會知道(而不是詢問他們出了什么問題").
One thing to add to what was said already is that it's paramount that you record any errors in your web application into a log. This way, as Jeff "Coding Horror" Atwood suggests, you'll know when your users are experiencing trouble with your app (instead of "asking them what's wrong").
為此,我推薦以下類型的基礎設施:
To do this, I recommend the following type of infrastructure:
- 在您的數據庫中創(chuàng)建一個崩潰"表和一組用于報告錯誤的包裝類.我建議為崩潰設置類別(阻塞"、安全"、PHP 錯誤/警告"(與異常)等).
- 在您的所有錯誤處理代碼中,確保記錄錯誤.始終如一地執(zhí)行此操作取決于您構建 API(上述步驟)的程度 - 如果操作正確,記錄崩潰應該微不足道.
額外的功勞:有時,您的崩潰將是數據庫級別的崩潰:即數據庫服務器關閉等.如果是這種情況,您的錯誤記錄基礎架構(以上)將失敗(您無法將崩潰記錄到數據庫中,因為日志嘗試寫入數據庫).在這種情況下,我會在您的 Crash 包裝器類中將故障轉移邏輯編寫為
Extra credit: sometimes, your crashes will be database-level crashes: i.e. DB server down, etc. If that's the case, your error logging infrastructure (above) will fail (you can't log the crash to the DB because the log tries to write to the DB). In that case, I would write failover logic in your Crash wrapper class to either
- 向管理員發(fā)送電子郵件,和/或
- 將崩潰的詳細信息記錄到純文本文件中
所有這些聽起來都有些矯枉過正,但相信我,這會影響您的應用程序是被接受為穩(wěn)定"還是不穩(wěn)定".這種差異源于這樣一個事實,即所有應用程序一開始都是不穩(wěn)定/崩潰的,但那些了解其應用程序所有問題的開發(fā)人員有機會實際修復它.
All of this sounds like an overkill, but believe me, this makes a difference in whether your application is accepted as a "stable" or "flaky". That difference comes from the fact that all apps start as flaky/crashing all the time, but those developers that know about all issues with their app have a chance to actually fix it.
這篇關于PHP 中的錯誤處理的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!