In this article I will explain with an example, how to display exception (error) Message details using JavaScript Alert MessageBox in ASP.Net using C# and VB.Net.
Exception details such as Message, StackTrace, TargetSite and Source will be displayed using JavaScript Alert MessageBox in ASP.Net.
 
 

HTML Markup

The HTML Markup consists of:
Button – For raise an Exception and the exception (error) Message details will be displayed.
<asp:Button Text="Click to Raise Exception" runat="server" OnClick="RaiseException" />
 
 

Display Exception (Error) Message details using JavaScript Alert MessageBox in ASP.Net

The following event handler is raised when the Button is clicked. An exception is raised by converting a string value to integer inside a Try-Catch block.
The raised Exception is caught in the Catch block and the details of the exception (error) are displayed using JavaScript Alert MessageBox.
C#
protected void RaiseException(object sender, EventArgs e)
{
    try
    {
        int i = int.Parse("Mudassar");
    }
    catch (Exception ex)
    {
        string message = string.Format("Message: {0}\\n\\n",ex.Message);
        message += string.Format("StackTrace: {0}\\n\\n"ex.StackTrace.Replace(Environment.NewLine, string.Empty));
        message += string.Format("Source: {0}\\n\\n"ex.Source.Replace(Environment.NewLine, string.Empty));
        message += string.Format("TargetSite: {0}"ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
        ClientScript.RegisterStartupScript(this.GetType(), "alert""alert(\"" + message + "\");"true);
    }
}
 
VB.Net
Protected Sub RaiseException(sender As Object, e As EventArgs)
    Try
        Dim i As Integer = Integer.Parse("Mudassar")
    Catch ex As Exception
        Dim message As String = String.Format("Message: {0}\n\n", ex.Message)
        message &= String.Format("StackTrace: {0}\n\n"ex.StackTrace.Replace(Environment.NewLine, String.Empty))
        message &= String.Format("Source: {0}\n\n"ex.Source.Replace(Environment.NewLine, String.Empty))
        message &= String.Format("TargetSite: {0}"ex.TargetSite.ToString().Replace(Environment.NewLine, String.Empty))
        ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert(""" & message & """);"True)
    End Try
End Sub
 
 

Screenshot

Display Exception (Error) Message details using JavaScript Alert MessageBox in ASP.Net
 
 

Demo

 
 

Downloads