C# 重载 try/catch
是否可以重载 C# 中的 try/catch 语句?如果做不到这一点,是否可以继承并做出类似的功能?
我们正在将 ELMAH 添加到现有网络应用程序,并且代码广泛使用 try/catches,显示错误在验证摘要中而不是显示错误页面。由于错误在 catch 语句中被捕获,ELMAH 假定错误正在被处理;事实上,它们只是以更美观的方式展示。
下面是它正在执行的操作的示例:
try
{
//code here...
}
catch (Exception ex)
{
customValidatorError.IsValid = false;
customValidatorError.ErrorMessage = ex.Message;
}
理想情况下,重载只会告诉 Elmah 通过 ErrorSignal.FromCurrentContext().Raise(e); 将异常添加到日志中
。在项目中使用时,我不想在每次使用时都添加该代码。为每个错误页面添加自定义错误页面而不是将错误添加到验证摘要中也超出了项目的范围。
Is it possible to overload the try/catch statements in C#? Failing that, is it possible to inherit and make similar functionality?
We are adding ELMAH to an existing web application and the code uses try/catches extensively, displaying errors in the validation summary instead of displaying error pages. As the errors are being caught in the catch statement ELMAH assumes that the errors are being dealt with; in actuality they are just being displayed in a more presentable manner.
Here is a sample of what it is doing:
try
{
//code here...
}
catch (Exception ex)
{
customValidatorError.IsValid = false;
customValidatorError.ErrorMessage = ex.Message;
}
Ideally the overload would just tell Elmah to add the exception to the logs via ErrorSignal.FromCurrentContext().Raise(e);
Due to the frequency this technique is used in the project I would prefer not to add that code to each and every time it is used. It is also beyond the scope of the project to add custom error pages for each error page instead of adding the errors to the validation summary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所发现的,将所有内容包装在 try/catch 中通常并不是您真正想要的。您最终会“吞掉”您可能想要记录在某处的异常。如果您确实想使用自定义验证器在页面上显示异常消息,您可能应该重新抛出异常,以便可以将其冒泡。 ASP.NET 将允许您设置“全局”错误处理。如果你想吞掉异常,你可以在一个地方做到这一点。如果您想向 ELMAH 发送信号或使用其他方法记录它们,您可以在一个地方执行此操作。这可以让你的异常处理保持干燥。
As you've found, wrapping everything in try/catch usually doesn't turn out to be what you really want. You end up "swallowing" exceptions that you probably want to log somewhere. If you do want to show the exception message on the page with a custom validator, you should probably re-throw the exception so that you can bubble that up. ASP.NET will allow you to setup "global" error handling. If you want to swallow the exceptions, you can do that in a single place. If you want to signal ELMAH or log them using another method, you can do so in a single place. This keeps your exception handling DRY.
使用像 log4net 这样的日志库来记录此类异常(记录它们确实不是直接处理它们,但是你正在使用异常处理 - 一旦捕获异常,它就被视为“已处理”)。
正如您所见,ELMAH 用于未处理的异常。
这两种方法相辅相成(ELMAH + 日志库)。
Use a logging library like log4net to log such exceptions (logging them is indeed not handling them directly, but you are using exception handling - as soon as you have caught an exception it is deemed "handled").
ELMAH is used for unhandled exceptions, as you have seen.
The two approaches complement each other (ELMAH + logging library).