Prevent outer exception from being discarded when thrown from BeginInvoke

前端 未结 3 871
陌清茗
陌清茗 2020-12-31 10:43

I have a handler for Application.ThreadException, but I\'m finding that exceptions aren\'t always getting passed to it correctly. Specifically, if I throw an exception-with-

3条回答
  •  佛祖请我去吃肉
    2020-12-31 11:37

    One way to do it is to put the inner-exception reference in a custom property or the Data dictionary -- i.e., leave the InnerException property null, and carry the reference some other way.

    Of course, this requires establishing some kind of convention that can be shared between the throwing code and the handling code. The best would probably be to define a custom exception class with a custom property, in a project that's referenced by both pieces of code.

    Sample code (though it needs more comments to explain why it's doing the crazy things it's doing):

    public class ExceptionDecorator : Exception {
        public ExceptionDecorator(Exception exception) : base(exception.Message) {
            Exception = exception;
        }
        public Exception Exception { get; private set; }
    }
    
    // To throw an unhandled exception without losing its InnerException:
    BeginInvoke(new Action(() => { throw new ExceptionDecorator(outer); }));
    
    // In the ThreadException handler:
    private void OnUnhandledException(object sender, ThreadExceptionEventArgs e) {
        var exception = e.Exception;
        if (exception is ExceptionDecorator)
            exception = ((ExceptionDecorator) exception).Exception;
        // ...
    }
    

提交回复
热议问题