ASP.NET – Error throwing or logging

此生再无相见时 提交于 2019-12-06 05:23:19
Jeff Sternal

If you can do something about an Exception in a given infrastructure layer, catch it there, handle it, then log it with your logging framework of choice if it's still appropriate to do so. For example, I've seen SqlExceptions in data access layers that represented deadlocks. Of course it would be better to eliminate the deadlocks, but until we could diagnose them it made sense to catch those Exceptions and retry a certain number of times.

If you cannot handle it at that level - if there's nothing sensible to do with it - don't catch it there. Just let it bubble up to the highest level context where you can do something about it, or if there's nothing you can do about it, let it bubble all the way to your executable / UI where you can log it and display something appropriate to the user (that is, not the stack trace or Exception message).

For additional details (and excellent advice) see this similar question, Should I catch exceptions only to log them?

We recently started working on some ASP.net applications. For the logging of errors we use log4net (based on log4j). With this dll you can call different kind of logging methods, like a fatal error or just an info message.

I suggest you should not throw errors from different layers. If an error occurs on that layer it should stay there and be logged on the appropriate location. Else this is a lot of work and it will ruin the maintainability of your application.

We always let the errors bubble to the top. Then we attach to the HttpApplication.Error event. At that point we decide what to do (i.e. log to the DB, file, show friendly message... etc).

I would do both:

  1. Log error where it happens, which is a MUST.
  2. Display to UI, depending on your choice, you can either display the full error message plus stack trace, or just display a customized friendly error message which provides enough information to look up the error you logged in step 1.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!