在项目中,后端接口如果不进行异常处理那遇到所有问题(后端中的问题)都会自动被处理成顶级异常并返回状态码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.