What#39;s the best way to handle the exceptions and how to deal with them in asp.net(处理异常的最佳方法是什么以及如何在 asp.net 中处理它们)
问题描述
首先,我已经熟悉简单的异常处理语法,但我想询问处理它们的最佳地点、最佳时间和最佳方式.
我正在构建一个 N 层应用程序.所以我认为 DAL 有时会产生一些错误来处理..我刚刚了解了 SqlException 类,该类有什么关系?我曾经看到过一段处理SqlException的代码,然后它处理了Exception!
I'm building an N-Layered application. 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 ? I once saw a code that handles the SqlException then it handles 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."
编辑
Page_Error
事件和 Application_Error
怎么样.. 我看到它们是处理错误的好习惯
EDIT
What about Page_Error
event and Application_Error
.. I saw that they are a good practice for handling errors
推荐答案
异常处理很重要,为此设计一个好的策略并不简单.
Exception handling is a big deal, and it's not simple to design a good strategy for that.
首先,一些通用规则:
- 当正在运行的代码完全无法继续运行时,就会发生异常,所以它可能试图处理一些内部异常但最终失败了.想想 TCP 连接:如果一个损坏的数据包到达,这是一个例外,但 TCP 协议可以处理它.如果损坏太多,则会抛出 I/O 或套接字异常
- 异常不能总是处理.在几乎所有情况下,当您从底层获得异常时,您将无法运行纠正代码.如果您的应用程序依赖于一个数据库并且处于离线状态,那么当您收到有关它的异常时,您只能显示一条错误消息
- 异常可能是意料之外的,并可能揭示设计或实施缺陷.例如,一个实现缺陷可能是这样的情况:您有一个冗余数据库,但当您无法连接到第一个镜像时,您不会尝试使用第二个
- 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. If too many are damaged, an I/O or socket exception is thrown
- 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.
考虑处理"例外.当您编写每一行代码时,请考虑可能会阻止它完成的问题,并考虑可能的纠正措施.如果有可能的话.错误信息不是一个好的处理方式,它是最新的策略.
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.
不要开始写try-catch(Exception),而是更喜欢特定的异常.如果您需要将字符串解析为数字等,则期望 FormatException
,如果您需要从 Object
转换为您的类型,则期望 InvalidCastException
Don't start to write try-catch(Exception), but prefer specific exceptions. If you need to parse strings to numbers etc, then expect FormatException
, if you need to cast from Object
to your type expect InvalidCastException
不要犹豫抛出异常!!不要像很多人那样做,即.return null
或使用(如 ANSI C)布尔返回值和引用参数.例外是有的.如果您可以处理异常(即您没有找到本地文件但您知道您有远程备份,那么通过调用远程镜像来处理 FileNotFoundException
,但如果您仍然无法连接然后最终抛出)然后执行并尝试恢复计算,但如果不能,则抛出.并且不要忘记抛出内部异常(如果存在),因为它有助于登录最高层.
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. 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. 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.
记住给消息足够的严重性.如果您通过代码发现您的数据库处于脱机状态,这并非意外异常.仍然将其记录为错误,但在调查日志时不要担心代码错误.相反,如果您捕获代码无法识别的异常(NullReferenceException
是一个经典示例),则以最高严重性记录,即.致命的,给它最大的优先级!
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. fatal, to give it maximum priority!
当然可以基于 Page.OnError
方法.如果您的站点的所有页面都有一个基页类,则绝对应该覆盖该方法.在这种方法中,您应该首先记录您的异常.
can surely be based upon Page.OnError
method. 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.
你也不应该滥用 try-catch(Exception) 块,因为如果你没有捕捉到一个你不能用 catch 处理的异常,你将必须通过 OnError 处理它.
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.
当您运行这样的方法时,不要立即考虑Server.RemoveError()
.对于 HTTP 500 错误(当未处理的异常冒泡到 ASP.NET 运行时时触发),您可以更喜欢使用静态 HTML 页面向用户显示礼貌消息.
When you run such a method, don't immediately think about 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.
- 如果发生任何奇怪的事情,请不要犹豫在底层
throw
- 正如您的建议所说,不要处理您无法处理的异常(如果您捕获了您无法处理的异常,则重新抛出它)
- LOG!!!!!!!!!!!!!!!!!!
- 不要在公共网站上向最终用户透露例外详情,永远不要!!默认情况下,ASP.NET 会阻止这种情况发生,但您仍然可以使用 OnError 打印堆栈跟踪
- 使用
OnError
或Application_Error
作为单一中心点来处理所有意外异常 - 根据错误/致命消息定期检查日志以发现代码问题,然后考虑维护/调试/修复它
- Don't hesitate to
throw
in underlying layers if anything strange occurs - 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)
- LOG!!!!!!!!!!!!!!!!!
- 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
- Use
OnError
, orApplication_Error
as single central point to handle all unexpected exceptions - Periodically examine logs against error/fatal messages to find issues with your code, then think about maintaining/debugging/fixing it
这篇关于处理异常的最佳方法是什么以及如何在 asp.net 中处理它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理异常的最佳方法是什么以及如何在 asp.net 中
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01