Click here to Skip to main content
Click here to Skip to main content

Use a custom exception object to handle JavaScript error messages

, 18 Sep 2010
Rate this:
Please Sign up or sign in to vote.
If you use JavaScipt to pop up error message boxes in your ASP.NET applications, then use a custom exception.
I frequently find ASP.NET code that has the same blocks of JavaScript repeated over and over again. A classic example is the script needed to pop up a message box.
 
The first thing that should be said is that message boxes should be avoided if at all possible. There are far better ways to handle the display of error messages.
 
If message boxes really are the way you want to go, then this tip might help.
 
The following is an example of a block of code that I see repeated again and again.
 
Dim messageStr As New StringBuilder
messageStr.Append _
    ("<script type='text/JavaScript'>AddOnload(function(){window.alert('")
messageStr.Append("Account Balance can not exceed credit limit');})</script>")
 
If (Not Page.ClientScript.IsClientScriptBlockRegistered("BalanceValidation")) Then
    Page.ClientScript.RegisterClientScriptBlock(GetType(String()), _
        "BalanceValidation", messageStr.ToString)
End If
 
Buried in the middle of that mess of JavaScript is the actual error message, which is all we should be thinking about when we want to throw an exception. We should not be wondering whether we've managed to get the magic sequence of ' ; ) } < and /. In fact, I'm not even sure whether I got these right in the above example.
 
What we want is to throw an exception and have the correct JavaScript wrapped around our error for us. Sounds like a job for a custom exception object.
 
The JSException class handles the dirty work of wrapping our error messages in JavaScript.
 
Public Class JSException
    Inherits ApplicationException
 
    Private Const JAVASCRIPT_WRAPPER As String = _
    "<script type='text/JavaScript'>AddOnload(function(){window.alert('{0}')});</script>"
 
    Public Sub ShowException(ByVal page As Page)
        If (Not page.ClientScript.IsStartupScriptRegistered("JSException")) Then
            page.ClientScript.RegisterStartupScript(GetType(String()), "JSException", AsJavaScriptMessage())
        End If
    End Sub
 
    Private Function AsJavaScriptMessage() As String
        ' Can't use string.format because of characters in Script String
        Return JAVASCRIPT_WRAPPER.Replace("{0}", Me.Message)
    End Function
 
    Public Sub New(ByVal message As String)
        MyBase.New(message)
    End Sub
End Class
 
You can throw a JSException as you would any exception.
 
Dim account As LoanAccount = GetAccount(accountNumber)
If (account.Balance + requiredAmount) > account.CreditLimit Then
    Throw New JSException("Account balance can not exceed Credit Limit")
End If
 
You can, of course, inherit from JSException, perhaps adding some useful parameters, like the account Number.
 
Private Sub DrawDownFunds(ByVal accountNumber As String, ByVal requiredAmount As Decimal)
    Dim account As LoanAccount = GetAccount(accountNumber)
    If (account.Balance + requiredAmount) > account.CreditLimit Then
        Throw New CreditLimitException(accountNumber)
    End If
End Sub
 
Displaying the exception is simple, thanks to the ShowException method on our base JSException class.
 
Try
    DrawDownFunds("XYZ005", 50000)
Catch ex As JSException
    ex.ShowException(Page)
End Try
 
This isn't rocket science, but it would be a big improvement over tediously constructing JavaScript strings and cutting and pasting them throughout your code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

No Biography provided

Comments and Discussions

 
Generaldddd Pinmemberway05146-Oct-10 16:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 18 Sep 2010
Article Copyright 2010 by Richard A. Dalton
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid