Intercepting an exception inside IDisposable.Dispose

前端 未结 11 1855
有刺的猬
有刺的猬 2020-12-13 02:07

In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper())
{
           


        
11条回答
  •  悲哀的现实
    2020-12-13 02:51

    In my case, I wanted to do this to log when an microservice crashes. I already have in place a using to properly clean up right before an instance shut down, but if that's because of an exception I want to see why, and I hate no for an answer.

    Instead of trying to make it work in Dispose(), perhaps make a delegate for the work you need to do, and then wrap your exception-capturing in there. So in my MyWrapper logger, I add a method that takes an Action / Func:

     public void Start(Action behavior)
         try{
            var string1 = "my queue message";
            var string2 = "some string message";
            var string3 = "some other string yet;"
            behaviour(string1, string2, string3);
         }
         catch(Exception e){
           Console.WriteLine(string.Format("Oops: {0}", e.Message))
         }
     }
    

    To implement:

    using (var wrapper = new MyWrapper())
      {
           wrapper.Start((string1, string2, string3) => 
           {
              Console.WriteLine(string1);
              Console.WriteLine(string2);
              Console.WriteLine(string3);
           }
      }
    

    Depending on what you need to do, this may be too restrictive, but it worked for what I needed.

提交回复
热议问题