Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I safely Debug.Assert in ASP.NET?

Tags:

c#

assert

asp.net

Asserts can't be caught. This is good because some errors I don't want to be wrapped in try/catch, at least not on the development server. But Asserts seem awefully dangerous. If they get onto production, it can hang the ASP.NET server with a msgbox.

//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

Is there better way to communicate an violation of a inviolable condition to a developer without risking hanging IIS?

UPDATE: After reading the first replies, I guess the answer hinges on a foolproof way to detect when code is running in a development environment and when it is on a production server, or figuring out how to throw an exception that can't be caught and ignored.

like image 410
MatthewMartin Avatar asked Apr 07 '10 20:04

MatthewMartin


2 Answers

I personally created a class called "Defense" with two methods, "Assert" and "Fail." Assert works similarly to xUnit "assert" in that it takes a boolean condition and a message and throws an exception with the message if the condition is false. Fail throws the exception right away.

It's super-simple and has saved my tuches many, many times. It's ASP.NET friendly and dies hard and fast. If you're concerned about these errors being thrown in the real world you can modify the Assert method so it logs instead using preprocessing directives (#if DEBUG ... #endif), but in my line of work I'd rather see hard errors in the real world than hide them and not know what happened.

like image 73
roufamatic Avatar answered Sep 23 '22 14:09

roufamatic


Don't really see the problem. Do like the first one and throw an exception. Then the server wont hang. Also you should never use debug.Assert in production(as you mentioned).

Throwing an exception will stop the execution aswell and you will be able to catch it. Just make sure that you log the exception and you will be fine with debugging.

like image 37
Oskar Kjellin Avatar answered Sep 23 '22 14:09

Oskar Kjellin