什么是分层中的应用程序中处理异常的建议的方法和最佳做法?
What is the suggested approach or best practice for handling exceptions in tiered applications?
- 您应该放在哪里的try / catch 块?
- 应该在哪里你实现日志记录?
- 是否有在n层应用程序管理异常的建议模式?
- Where should you place try/catch blocks?
- Where should you implement logging?
- Is there a suggested pattern for managing exceptions in n-tiered applications?
考虑一个简单的例子。假设你有一个用户界面,调用业务层,调用数据层:
Consider a simple example. Suppose you have a UI, that calls a business layer, that calls a data layer:
//UI protected void ButtonClick_GetObject(object sender, EventArgs e) { try { MyObj obj = Business.GetObj(); } catch (Exception ex) { Logger.Log(ex); //should the logging happen here, or at source? MessageBox.Show("An error occurred"); } } //Business public MyObj GetObj() { //is this try/catch block redundant? try { MyObj obj = DAL.GetObj(); } catch (Exception ex) { throw new Exception("A DAL Exception occurred", ex); } } //DAL public MyObj GetObj() { //Or is this try/catch block redundant? try { //connect to database, get object } catch (SqlException ex) { throw new Exception("A SQLException occurred", ex); } }
你会做什么批评的上述异常处理?
What criticisms would you make of the above exception handling?
感谢
推荐答案我的经验法则通常捕捉异常是在顶层和日志(或其他报告)他们那里,因为这是你对错误最多的信息 - 最重要的是完整的堆栈跟踪
My rule of thumb is generally to catch exceptions at the top level and log (or otherwise report) them there, because this is where you have the most information about the the error - most importantly the full stack trace.
可能有一些原因赶在其他层的例外,但是:
There may be some reasons to catch exceptions in other tiers, however:
登录在多个层次相同的错误一般是没有什么用处,但我能想到的一个例外的:当下层不知道问题是否严格或不它可以记录它作为一个警告。如果一个更高层次的决定,它的是的关键就可以登录同样的问题,因为一个错误。
Logging the same error at multiple tiers is generally not useful, but I can think of one exception: when a lower tier doesn't know whether a problem is critical or not it can log it as a warning. If a higher tier decides that it is critical it can then log the same problem as an error.
更多推荐
在n层应用程序异常处理?
发布评论