Saturday, September 19, 2009

Making ASP “Die” like PHP

How clever was that title!  Not clever.  I know.  Oh well.

So, PHP has the age-old “die()” function to stop processing and puke up a message in the process.  Great for most general needs.  When you want the page to crash-out gracefully and say something intuitive and elegant to the user, like “hey, you fucked up, you idiot!”  Just kidding.  ASP doesn’t really have an identical function, but it does have the Response.End object method.  So you can make a really simple function (ok, Sub) to do pretty much the same thing.

Sub Die(strMessage)
If strMessage = "" Then
strMessage = "processing stopped."
End If
Response.Write "<span style="color: red; font-weight: bold">" & strMessage & "</span>"
End Sub

' example of usage
If Session("LoggedOn") <> "TRUE" Then
Die "logon failure!"
End If

When would you want to use this?  One good example is on pages where you want to ensure some global condition exists before rendering the page.  A good example of that would be checking to see if the user is “logged in” or “validated” or a quantity in a form was selected, or whatever.  Maybe you want to ensure a page is only called from a specific other page, and not directly.  You can pass a hidden form object or querystring to shake hands, but if a sneaky asswipe user decides to shortcircuit your site by calling the second page directly, you can check for that form/querystring input and gracefully crash-out if it’s not provided.  I’m sure if you smoke enough of something you can think of other possible uses.  But this hopefully helps you in some random remote way.

Post a Comment