如何在 ASP.NET 中安全地进行 Debug.Assert?

Mat*_*tin 5 c# asp.net assert

无法捕获断言。这很好,因为我不想将某些错误包含在 try/catch 中,至少不在开发服务器上。但断言似乎非常危险。如果他们投入生产,它可以使用 msgbox 挂起 ASP.NET 服务器。

//Don't want this on prod even if debug=true is in the web.config
#if DEBUG
    //A future client programmer can wrap this in a try{}catch{}
    if (!EverythingIsOkay)
        throw new InvalidOperationException("Dagnabbit, programming error");

    //This stops the but has less information that an
    // Exception and hangs the server if this accidentally 
    // runs on production
    System.Diagnostics.Debug.Assert(!EverythingIsOkay);
#endif
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法可以向开发人员传达违反不可侵犯条件的情况,而不会冒 IIS 挂起的风险?

更新:阅读第一个回复后,我想答案取决于一种万无一失的方法来检测代码何时在开发环境中运行以及何时在生产服务器上运行,或者弄清楚如何抛出无法捕获的异常并被忽略。

rou*_*tic 2

我亲自创建了一个名为“Defense”的类,它有两种方法:“Assert”和“Fail”。Assert 的工作方式与 xUnit“assert”类似,它接受一个布尔条件和一条消息,如果条件为 false,则抛出带有消息的异常。失败立即抛出异常。

它非常简单,并且多次节省了我的时间。它对 ASP.NET 友好并且很快就会消失。如果您担心现实世界中抛出这些错误,您可以修改 Assert 方法,以便它使用预处理指令 ( #if DEBUG ... #endif) 进行记录,但在我的工作中,我宁愿看到现实世界中的硬错误,也不愿隐藏它们并且不知道发生了什么。