简体   繁体   English

什么是处理异常以及如何在asp.net中处理它们的最佳方法

[英]What's the best way to handle the exceptions and how to deal with them in asp.net

First, I'm already familiar with the simple exception handling syntax but I'm asking about the best place, the best time and the best way to deal with them. 首先,我已经熟悉了简单的异常处理语法,但我要问的是最佳位置,最佳时间以及处理它们的最佳方法。

I'm building an N-Layered application. 我正在构建一个N层应用程序。 so I think the DAL will sometime generate some errors to handle .. and I just learned about the SqlException class, what's the deal with that class ? 所以我认为DAL有时会产生一些错误来处理..而我刚刚了解了SqlException类,该类的处理是什么? I once saw a code that handles the SqlException then it handles Exception! 我曾经看过一个处理SqlException的代码,然后它处理Exception!

After knowing the practice and where I'm going to handle them, I'm planning to create a method to connect to the database and log the errors in a database so I could fix it but still I don't know what information should I collect to allow me identify the whole situation! 在了解了实践以及我将要处理它们之后,我计划创建一个连接数据库并在数据库中记录错误的方法,以便我可以解决它,但我仍然不知道应该提供哪些信息收集让我识别整个情况!


I thought exceptions handling was not a big deal. 我认为异常处理并不是什么大问题。 but every now and then I read some strange advices -that I never understood- on the questions comments but no one could answer me since it was some very old questions! 但我时不时地读到一些奇怪的建议 - 我从未理解 - 在问题评论中但是没有人能回答我,因为这是一些非常古老的问题!

"Don't just explicitly catch exceptions" “不要只是明确地捕捉异常”

"the code that is used by higher-layers in your application must always only throw exceptions and never worry about how to deal with them." “应用程序中更高层使用的代码必须始终只抛出异常,而不必担心如何处理它们。”

EDIT 编辑

What about Page_Error event and Application_Error .. I saw that they are a good practice for handling errors 那么Page_Error事件和Application_Error ..我看到它们是处理错误的好习惯

Exception handling is a big deal, and it's not simple to design a good strategy for that. 异常处理是一个大问题,为此设计一个好的策略并不简单。

First of all, some general rules: 首先,一些一般规则:

  • Exceptions occur when the running code is completely unable to go ahead, so maybe it tried to handle some internal exceptions but ultimately failed. 当正在运行的代码完全无法继续时,会发生异常,因此可能会尝试处理一些内部异常,但最终会失败。 Think about TCP connection: if a damaged packet arrives, it's an exception, but TCP protocol can handle it. 想想TCP连接:如果损坏的数据包到达,它是一个例外,但TCP协议可以处理它。 If too many are damaged, an I/O or socket exception is thrown 如果太多损坏,则抛出I / O或套接字异常
  • Exceptions can not always be handled . 无法始终处理例外情况。 In almost all cases, when you get an exception from underlying layers you are unable to run corrective code. 几乎在所有情况下,当您从底层图层获得异常时,您无法运行更正代码。 If your application depends on a DB and that is offline, when you get the exception about it you can only display an error message 如果您的应用程序依赖于数据库且处于脱机状态,则当您获得有关它的例外时,您只能显示错误消息
  • Exceptions can be unexpected, and can reveal design or implementation flaws. 例外可能是意料之外的,并且可能揭示设计或实施缺陷。 For example, an implementation flaw can be the situation in which you have a redundant DB but when you fail to connect to frist mirror you don't try with the second 例如,一个实现缺陷可能是你有一个冗余数据库的情况,但是当你连接到第一个镜像时你没有尝试第二个

For the third point, it's important to log exceptions and periodically analyse logs to find any weird situation. 对于第三点, 记录异常并定期分析日志以查找任何奇怪的情况非常重要。 So, let's begin with the concrete answer. 那么,让我们从具体的答案开始吧。

First of all 首先

think about "handling" the exception. 想想“处理”异常。 When you write every single code line, think about the possible problems that may prevent it from completing, and think about the possible corrective actions . 当您编写每个代码行时,请考虑可能阻止其完成的可能问题,并考虑可能的纠正措施 if any are possible. 如果可能的话。 An error message is not a good handling way, it's the latest strategy. 错误消息不是一种好的处理方式,这是最新的策略。

Don't start to write try-catch(Exception), but prefer specific exceptions. 不要开始编写try-catch(Exception),但更喜欢特定的异常。 If you need to parse strings to numbers etc, then expect FormatException , if you need to cast from Object to your type expect InvalidCastException 如果你需要将字符串解析为数字等,那么期望FormatException ,如果你需要从Object InvalidCastException为你的类型期望InvalidCastException

When you write lower-level layers 编写较低级别的图层时

don't hesitate to throw exceptions!! 不要犹豫,抛出异常! Don't do like many folks do, ie. 不要像许多人那样做,即。 return null or use (like ANSI C) a boolean return value and reference parameters. return null或使用(如ANSI C)布尔返回值和引用参数。 Exceptions are there for that. 有例外。 If you can handle an exception (ie. you don't find a local file but you know you have a remote backup, so handle FileNotFoundException by calling the remote mirror, but if you can't still connect then ultimately throw) then do it and try to resume computation, but if you cannot then throw. 如果你可以处理异常(即你没有找到本地文件,但你知道你有远程备份,那么通过调用远程镜像处理FileNotFoundException ,但如果你仍然无法连接,那么最终抛出)然后执行它并尝试恢复计算,但如果你不能然后扔。 And don't forget to throw the inner exception, if present, because it is helpful for logging in the highest layer. 并且不要忘记抛出内部异常(如果存在),因为它有助于登录最高层。

Basically, you can still decide to throw an exception on your own even if you don't catch any! 基本上,即使你没有抓到任何东西,你仍然可以决定自己抛出异常! And this is highly recommended especially when function parameters are invalid! 特别是当功能参数无效时,强烈建议这样做!

Another good option is to still log in the underlying layers. 另一个不错的选择是仍然登录底层。 You actually want to log no matter an exception occurs. 无论发生异常,您实际上都想记录。

When you log 当你记录

remember to give an adequate severity to the messages. 记得给消息一个足够的严重性。 If you find via code that your DB is offline, that's not an unexpected exception. 如果您通过代码发现数据库处于脱机状态,那么这不是意外的异常。 Still log it as an error, but don't worry about code bugs when you investigate the logs. 仍然将其记录为错误,但在调查日志时不要担心代码错误。 Instead, if you catch an exception that your code is unable to recognize (a NullReferenceException is a classic example) then log with highest severity, ie. 相反,如果您捕获到代码无法识别的异常( NullReferenceException是一个典型示例),则以最高严重性记录,即。 fatal, to give it maximum priority! 致命的,给予它最大的优先权!

A good strategy for ASP.NET ASP.NET的一个好策略

can surely be based upon Page.OnError method. 肯定可以基于Page.OnError方法。 If you have a base page class for all of the pages of your site, you should definitely override that method. 如果您的站点的所有页面都有基页类,那么您绝对应该覆盖该方法。 In that method, you should first log your exception. 在该方法中,您应该首先记录您的异常。

You also shouldn't abuse of try-catch(Exception) blocks, because if you don't catch an exception you can't handle with catch, you will have to handle it via OnError. 您也不应该滥用try-catch(异常)块,因为如果您没有捕获异常,则无法使用catch处理,您不得不通过OnError处理它。

When you run such a method, don't immediately think about Server.RemoveError() . 运行这样的方法时,不要立即考虑Server.RemoveError() You can prefer to have a static HTML page for HTTP 500 error (that is triggered when an unhandled exception bubbles to ASP.NET runtime) that displays a courtesy message to the user. 您可能更喜欢为HTTP 500错误(当未处理的异常冒泡到ASP.NET运行时时触发)的静态HTML页面向用户显示礼貌消息。

Briefly 简要地

  1. Don't hesitate to throw in underlying layers if anything strange occurs 如果发生任何奇怪的事情,请毫不犹豫地throw底层
  2. As said by your advice, don't handle exceptions you are unable to handle (if you catch an exception you can't handle, rethrow it) 正如你的建议所说,不要处理你无法处理的异常(如果你遇到一个你无法处理的异常,请重新抛出它)
  3. LOG!!!!!!!!!!!!!!!!! LOG !!!!!!!!!!!!!!!!!
  4. Don't disclose exception details to final users on a public website, never!! 不要在公共网站上向最终用户透露异常详细信息,永远不要! By default, ASP.NET prevents that from occurring, but you could still use OnError to print stack trace 默认情况下,ASP.NET会阻止它发生,但您仍然可以使用OnError来打印堆栈跟踪
  5. Use OnError , or Application_Error as single central point to handle all unexpected exceptions 使用OnErrorApplication_Error作为单个中心点来处理所有意外异常
  6. Periodically examine logs against error/fatal messages to find issues with your code, then think about maintaining/debugging/fixing it 定期检查日志以查找错误/致命消息以查找代码问题,然后考虑维护/调试/修复它

Take a look at elmah. 看看elmah。 It's a logger for asp.net. 它是asp.net的记录器。 Renders all errors on a nice summary page. 在一个漂亮的摘要页面上呈现所有错误。

http://code.google.com/p/elmah/ http://code.google.com/p/elmah/

The best way to handle exceptions is in the specific layer they apply to. 处理异常的最佳方法是在它们适用的特定层中。 If it is a constraint volation, for example, 2 users with the same name, you should let that bubble up to the UI and alert the user. 如果它是一个约束声音,例如,2个具有相同名称的用户,则应该将该气泡提升到UI并提醒用户。

Same goes with any business rule violations. 违反任何业务规则也是如此。 Those should bubble up to the UI so the end user knows what went wrong. 这些应该冒泡到UI,以便最终用户知道出了什么问题。

A SQL Connectivity error is best handled in the DAL...etc.. SQL连接错误最好在DAL ...等处理。

The how/when/where to catch exceptions may depend on what your trying to do exactly, its difficult to give an exact catch all always correct answer. 捕获异常的方式/时间/位置可能取决于您尝试做什么,难以准确捕获所有始终正确的答案。


As to your specific questions, 至于你的具体问题,

I just learned about the SqlException class, what's the deal with that class ? 我刚刚了解了SqlException类,该类的处理是什么? I once saw a code that handles the SqlException then it handles Exception! 我曾经看过一个处理SqlException的代码,然后它处理Exception!

Its good practice to handle the specific exception you believe may occur, if your not sure what type this exception is you can just 'Exception', if you want something specific to occur on a 'SQLException' and something else to happen with an 'Exception' then there is certainly nothing wrong with writing code that handles both. 处理你认为可能发生的特定异常的好习惯,如果你不确定这个异常是什么类型,你可以只是'异常',如果你想在'SQLException'上发生特定的事情,那么'异常会发生'异常'那么编写处理这两者的代码肯定没有错。


"Don't just explicitly catch exceptions" “不要只是明确地捕捉异常”

I believe this is refering to code like this 我相信这是指代这样的代码

try 
{
   int i = 1/0;
} 
catch(Exception e)
{
  //do nothing
}

This exception will be caught but you'll never know it happened, hence this is not a good idea, and the person using the code will be scratching their head as to whats going on. 这个例外将被捕获,但你永远不会知道它发生了,因此这不是一个好主意,并且使用该代码的人将会摸不着头脑。

I think what you are asking here is a Error/Exception Handling Strategy for any application. 我想你在这里问的是任何应用程序的错误/异常处理策略。

I think it includes: 我认为它包括:

Where - All places where you think an exception can occur or which need more monitoring like DB calls, External Service Calls, Use of Arrays, User Input Parsing, Type Casting and so on... Where - 您认为异常可能发生或需要更多监控的所有地方,如数据库调用,外部服务调用,数组使用,用户输入解析,类型转换等等......

How - All you high level layers should throw the exception and it should be captured at the entry point and processed to understand the root cause. 如何 - 所有高级别层都应该抛出异常,应该在入口点捕获它并进行处理以了解根本原因。 Usually you do this in Application_Error() where you catch the exception and log it for troubleshooting. 通常,您可以在Application_Error()中执行此操作,捕获异常并将其记录以进行故障排除。 How you log an exception is upto you. 如何记录异常取决于您。 A Log File or DB driven log is an option based on your requirements and available resources. 日志文件或数据库驱动的日志是基于您的要求和可用资源的选项。

IMO apart from extremely rare circumstances I only ever use exception handling for I/O related code where there are interactions with services and file systems whose functionality and maintenance is beyond the control of my applications. IMO除了非常罕见的情况外,我只对I / O相关代码使用异常处理,其中存在与服务和文件系统的交互,其功能和维护不受我的应用程序的控制。

I have always considered the use try/catch statements to manipulate the logic (flow-of-control) in a program in the same way if/else statement work to be extremely bad practice. 我总是考虑使用try / catch语句以相同的方式操作程序中的逻辑(控制流),如果/ else语句工作非常糟糕的话。 Most common exceptions can be avoided if you use the tools at hand correctly. 如果您正确使用手头的工具,可以避免最常见的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.Net中处理web.config文件版本的最佳方法是什么? - What's the best way to handle web.config file versions in ASP.Net? 在ASP.Net应用程序中处理长时间运行的最佳方法是什么? - What's the best way to handle long running process in an ASP.Net application? 针对Ajax请求的Asp.Net MVC操作中处理未处理的异常(错误500响应)的最佳策略是什么? - What is the best strategy to handle unhandled Exceptions (error 500 responses) in Asp.Net MVC actions for Ajax requests? 在 ASP.NET 上检测 JSON 请求的最佳方法是什么 - What's the best way to detect a JSON request on ASP.NET 在ASP.NET中检查用户浏览器的最佳方法是什么? - What is the best way to check the user's browser in ASP.NET? 在ASP.NET中显示缩略图的最佳方法是什么? - What's the best way of displaying thumbnails in ASP.NET? 如何在服务器端捕获 ASP.NET Core 2 SignalR 异常并在客户端使用 JavaScript 处理它们? - How to catch ASP.NET Core 2 SignalR exceptions on server-side and handle them on client side with JavaScript? 在代码的整个生命周期中处理异常的最佳方法是什么? - What's the best way to handle exceptions over the lifetime of your code? 在 C# 中处理异步 HttpWebRequest 异常的最佳方法是什么? - What's the best way to handle asynchronous HttpWebRequest exceptions in C#? ASP.NET MVC中的values参数处理什么? - What's the deal with values parameter in ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM