更好的识别corruptedstateexception的方法



让我们用更少的开销再试一次:

如何确定异常是否为CorruptedStateException?

据我所知,没有共同的超类,所有的CorruptedStateExceptions继承(独家),我发现没有其他的属性/标志/属性,我可以用来识别他们。

目前我能提出的最好的是在2个步骤中工作:在以下情况下,ThirdPartyCall具有属性[HandleProcessCorruptedStateExceptions][SecurityCritical]设置捕捉CorruptedStateExceptions,而ThirdPartyCallInternal没有。如果ThirdPartyCallInternal捕获一个异常,它不是CSE,如果只有ThirdPartyCall捕获它,它是一个。

[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public static void ThirdPartyCall()
{
    bool thrownExceptionIsCorruptedState = true;
    try
    {
        ThirdPartyCallInternal(ref thrownExceptionIsCorruptedState);
    }
    catch (Exception ex)
    {
        if (thrownExceptionIsCorruptedState)
        {
            //This is pretty much the only thing we'd like to do...
            log.Fatal("CorruptedStateException was thrown",ex);
        }
        throw;
    }
}
private static void ThirdPartyCallInternal(ref bool thrownExceptionIsCorruptedState)
{
    try
    {
        ThirdPartyLibrary.DoWork();
    }
    catch (Exception)
    {
        //Exception was caught without HandleProcessCorruptedStateExceptions => it's not a corruptedStateException
        thrownExceptionIsCorruptedState = false;
        throw;
    }
}

是否有其他(更干净,更容易,…)的方法来确定一个异常是否是一个会使应用程序崩溃的CorruptedStateException ?

可能有一个误解:"损坏状态"更像是任何其他类型异常的标志,而不是异常本身。因此你的语句

log.Fatal("CorruptedStateException was thrown",ex);

是不正确的。没有抛出类型为CorruptedStateException的异常。例如,真正的异常类型可以是AccessViolationException,你应该研究一下它的原因。

因此,我认为异常是否是损坏状态异常并不重要。重要的是,你的应用程序实际捕获异常,你得到通知,你可以修复它。

这样做可以将代码简化为

[HandleProcessCorruptedStateExceptions]
[SecurityCritical]
public static void ThirdPartyCall()
{
    try
    {
        ThirdPartyLibrary.DoWork();
    }
    catch (Exception ex)
    {   
        //This is pretty much the only thing we'd like to do...
        log.Fatal("Exception was thrown",ex);
        Environment.FailFast("Fatal exception in 3rd party library");
    }
}

除此之外,也许最好让操作系统处理这个崩溃,而不是试图写一些东西到日志文件中。请注意,log4net也可能已经被销毁,无法再写入日志文件。

相反,注册Windows错误报告,从微软获取崩溃转储并分析它们。

相关内容

最新更新