简体   繁体   English

是否有任何事件在发生异常时被触发?

[英]Is there any event which gets triggered whenever there is an exception?

Is there any event in .Net framework which gets fired on exception. 在.Net框架中是否有任何事件被异常触发。 Whenever there is an exception is caught, i need to log it. 每当有异常被捕获时,我都需要记录它。 So if there an event exist, i can subscribe to that and can log the exceptio in the event handler. 因此,如果存在事件,我可以订阅它并且可以在事件处理程序中记录异常。

Yes - there is the UnhandledException event on the AppDomain object: 是的 - AppDomain对象上有UnhandledException事件:

AppDomain.CurrentDomain.UnhandledException += YourHandler

FYI: You should only use these handlers as a last resort - it is far better to catch exceptions in a try catch block, although this may not always be possible (for example in the case when 3rd party code starts new threads) 仅供参考:你应该只使用这些处理程序作为最后的手段 - 在try catch块中捕获异常要好得多,尽管这可能并不总是可行的(例如在第三方代码启动新线程的情况下)

Also, this event will only be fired when an exception is unhandled - to my knowledge there is no way of being notified of caught events in this way without attaching a debugger to the process. 此外,只有在未处理异常时才会触发此事件 - 据我所知,如果不将调试器附加到进程,就无法以这种方式通知捕获的事件。

You should have a look at doing some Aspect Oriented Programming with PostSharp, you can write a simple Log attribute and apply it to your whole assembly. 您应该看一下使用PostSharp进行面向方面编程,您可以编写一个简单的Log属性并将其应用于整个程序集。

All you need is something like this: 你需要的只是这样的:

[Serializable]
public class LogAttribute : OnMethodInvocationAspect
{
   public override void OnInvocation(MethodInvocationEventArgs eventArgs)
   {
      try
      {
         eventArgs.Proceed();
      }
      catch(Exception ex)
      {
         // log exception here
      }
   }
}

and apply it to your assembly: 并将其应用于您的程序集:

[assembly: Log]
public class ...

It's not everyone's cup of tea, but I've found it a very clean, neat way to avoid doing a lot of boilerplate code in my classes and frees me up to work on functionalities more related to the project itself. 这不是每个人的一杯茶,但我发现它是一种非常干净,整洁的方式,以避免在我的课程中做很多样板代码,并让我从事与项目本身更相关的功能。

Update: as Kugel pointed out in the comment, this will help you track and log any exceptions thrown during the execution of the method, but if you want to log the state internal to the method you'll need to do a little more work than this. 更新:正如Kugel在评论中指出的,这将帮助您跟踪和记录在执行方法期间抛出的任何异常,但是如果您想要记录方法内部的状态,则需要做更多的工作而不是这个。

For instance, you might still need try/catch blocks inside your method which you could use to capture exceptions that are of interest to your class and maybe even wrap them in a custom exception object so you can start adding more useful information like an error code, etc. So long your custom exception has a suitable mechanism of setting its 'Message' property, eg 例如,您可能仍然需要在方法中使用try / catch块,您可以使用它来捕获类所感兴趣的异常,甚至可以将它们包装在自定义异常对象中,这样您就可以开始添加更多有用的信息,如错误代码等等。你的自定义异常有一个合适的机制来设置它的'Message'属性,例如

public class DictionaryKeyNotValidException() : Exception
{
   public DictionaryKeyNotValidException(string key)
       : base(GetMessage(key))
   {   
   }

   public ErrorEnum ErrorCode { get { return ErrorEnum.InvalidDictionaryKey; } }

   private string GetMessage(string key)
   {
      return string.Format("ERROR {0} : Invalid dictionary key encountered {1}",
                           ErrorCode.GetHashCode(), key);
   }
}

then in your log attribute, provided you're using Log4Net, you can start logging more useful information: 然后在您的日志属性中,如果您使用的是Log4Net,则可以开始记录更多有用的信息:

catch (Exception ex)
{
   // log error
   log.Error(ex);

   // handle exception, rethrow, etc.
   ...
}

Sorry this is becoming a bit long winded.. 对不起,这有点长啰嗦..

Besides the Exception ? 除了Exception I'd just add a call to my logging module into my catch block. 我只是将我的日志模块调用添加到我的catch块中。

Something like: 就像是:

catch(YourException ex)
{
  LogMyException(ex, [otherParamsYouNeed]);
  //Other Exception Handling
}

If you want to log the status of something regardless of success or failure, use finally{} 如果要记录某些内容的状态而不管成功或失败,请使用finally{}

In WinForms you have the Application.ThreadException event and more general there is the AppDomain.CurrentDomain.UnhandledException event. 在WinForms中,您有Application.ThreadException事件,更常见的是AppDomain.CurrentDomain.UnhandledException事件。

But please note that after logging these exceptions the advised thing to do is close the application. 但请注意,在记录这些异常后,建议要做的就是关闭应用程序。 It may no longer be in a stable state. 它可能不再处于稳定状态。

AppDomain类有一个UnhandledException事件,但我认为你不能订阅任何抛出异常。

look at this http://www.switchonthecode.com/tutorials/csharp-tutorial-dealing-with-unhandled-exceptions UnhandledExceptionEventHandler is what you are looking for this is with windows from but i think there is similar think for the web too 看看这个http://www.switchonthecode.com/tutorials/csharp-tutorial-dealing-with-unhandled-exceptions UnhandledExceptionEventHandler就是你正在寻找的这个是来自windows但我认为也有类似的想法对于网络来说
Best Regards, 最好的祝福,
Iordan 约尔丹

In ASP.NET, unhandled exceptions can be caught at the page level by handling the Page_Error event, or at the application level (in global.asax, or in an IHttpModule implementation) by handling Application Error events. 在ASP.NET中,可以通过处理Page_Error事件在页面级别捕获未处理的异常,或者通过处理应用程序错误事件在应用程序级别(在global.asax或IHttpModule实现中)捕获未处理的异常。 These events don't give you the actual exception, so you'll need to call the server to get the exception: 这些事件不会给你实际的异常,因此你需要调用服务器来获取异常:

    Exception ex = HttpContext.Current.Server.GetLastError();

To extend on the answer given by theburningmonk, you could also try using log4PostSharp . 要扩展theburningmonk给出的答案,您还可以尝试使用log4PostSharp This is pre-built code that uses PostSharp to insert logging code that works with the log4net logging framework. 这是使用PostSharp插入与log4net日志记录框架一起使用的日志记录代码的预构建代码。

Amongst other things this will automatically add code to your methods that catches exceptions and logs them. 除此之外,它还会自动将代码添加到捕获异常并记录异常的方法中。

It all depends on whether you are happy to use the log4net logging framework or would prefer to do it yourself. 这完全取决于您是否乐意使用log4net日志记录框架或者更愿意自己做。

In vb.net, one can add a "When" qualifier to a catch statement (eg 'Catch Ex as ObjectDisposedException When Ex.Message.Contains("Sorry")'). 在vb.net中,可以向catch语句添加“When”限定符(例如,当Ex.Message.Contains(“Sorry”)'时,'Catch Ex as ObjectDisposedException')。 This may be used for logging putposes (eg 'Catch Ex as Exception When LoggingFunctionThatReturnsFalse(Ex)' won't catch any exceptions, but will log them all) and seems like a feature that would have been useful in C#. 这可以用于记录putposes(例如'Catch Ex as Exception当LoggingFunctionThatReturnsFalse(Ex)'不会捕获任何异常,但会将它们全部记录下来)并且看起来像是一个在C#中有用的功能。 Last I heard, though, the feature was only available in vb.net (not sure what would happen if one compiled code using such a feature in vb.net and decompiled to C#). 最后我听说,该功能仅在vb.net中可用(不确定如果在vb.net中使用这样的功能编译代码并反编译为C#会发生什么)。

You could put something in the Global.asax Application_Error event. 您可以在Global.asax Application_Error事件中添加一些内容。

I've used this method to do exactly what you described in the original post, logging the error and emailing a notification. 我已经使用此方法完成您在原始帖子中描述的内容,记录错误并通过电子邮件发送通知。

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

相关问题 为什么未为引发异常的Task触发UnobservedTaskException事件处理程序? - Why is the UnobservedTaskException event handler not triggered for a Task which throws an exception? 有什么方法可以创建一个事件,只要将刚体设为Kinematic True,就可以启动功能? - Is there any way to create an event which starts a Function whenever the Rigidbody is made Kinematic True? 超时结束后触发事件 - Event gets triggered after timeout is over 有没有办法在抛出CLR异常时触发事件 - Is there a way to fire an event whenever a CLR exception is thrown 与自定义事件触发器一起使用时,不会触发MouseLeftButton事件 - MouseLeftButton event doesnt gets triggered when used with Custom Event Trigger 触发事件时在函数调用中引发异常 - Raise exception in function call when event is triggered 事件被触发而没有任何声明 - Event being triggered without any declaration 如何确定哪个键触发了 RoutedCommand 事件 - How to determine which key triggered RoutedCommand event Gridview OnRowCreated事件被触发多次-dropdownlist被填充两次 - Gridview OnRowCreated event gets triggered multiple times - dropdownlist gets populated twice 将新窗口添加到桌面时是否触发任何事件 - Is there any event triggered when a new window is added to the desktop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM