在項目中,後端接口如果不進行異常處理那遇到所有問題(後端中的問題)都會自動被處理成頂級異常並返回狀態碼500(server internal error),這樣無論是Debug還是前端提示用戶都不清楚。
異常處理的好處
對於整個代碼邏輯,如果沒有在底層進行異常處理,異常就會一級一級往上拋,直到最外層的。
如果在一個大的系統或服務代碼中,不能因爲一個小bug就導致整個功能停止。可以預見到的局部且不會影響後續代碼邏輯的異常就在本地接受並進行處理,將出現的異常記錄到log中,僅有coder可以在日誌中進行查看看。如果是會影響到後續代碼執行或者是嚴重的錯誤,就直接在local讓程序停下來沒必要繼續執行了。
建議的做法
-
To catch all unhandled exceptions by hooking to the
Application.ThreadException event
, then decide :- For a UI application: to pop it to the user with an apology message (winforms)
- For a Service or a Console application: log it to a file (service or console)
Then I always enclose every piece of code that is run externally in try/catch
:
- All events fired by the Winforms infrastructure (Load, Click, SelectedChanged...)
- All events fired by third party components
Then I enclose in 'try/catch'
- All the operations that I know might not work all the time (IO operations, calculations with a potential zero division...). In such a case, I throw a new
ApplicationException("custom message", innerException)
to keep track of what really happened
Additionally, I try my best to sort exceptions correctly. There are exceptions which:
- need to be shown to the user immediately
- require some extra processing to put things together when they happen to avoid cascading problems (ie: put .EndUpdate in the
finally
section during aTreeView
fill) -
the user does not care, but it is important to know what happened. So I always log them:
- In the event log
- or in a .log file on the disk
It is a good practice to design some static methods to handle exceptions in the application top level error handlers.
I also force myself to try to:
- Remember ALL exceptions are bubbled up to the top level. It is not necessary to put exception handlers everywhere.
- Reusable or deep called functions does not need to display or log exceptions : they are either bubbled up automatically or rethrown with some custom messages in my exception handlers.