Click here to Skip to main content
15,881,248 members
Articles / Web Development / ASP.NET
Tip/Trick

Use a custom exception object to handle JavaScript error messages

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
18 Sep 2010CPOL1 min read 12.6K   3   1
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.

VB
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.

VB
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.

VB
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.

VB
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.

VB
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)


Written By
Ireland Ireland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generaldddd Pin
way05146-Oct-10 16:48
way05146-Oct-10 16:48 

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

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