Question

I have an ASP.NET web application, and I wanted to know how I could display an error message box when an exception is thrown.

For example,

        try
        {
            do something
        }
        catch 
        {
            messagebox.write("error"); 
            //[This isn't the correct syntax, just what I want to achieve]
        }

[The message box shows the error]

Thank you

Was it helpful?

Solution

You can't reasonably display a message box either on the client's computer or the server. For the client's computer, you'll want to redirect to an error page with an appropriate error message, perhaps including the exception message and stack trace if you want. On the server, you'll probably want to do some logging, either to the event log or to a log file.

 try
 {
     ....
 }
 catch (Exception ex)
 {
     this.Session["exceptionMessage"] = ex.Message;
     Response.Redirect( "ErrorDisplay.aspx" );
     log.Write( ex.Message  + ex.StackTrace );
 }

Note that the "log" above would have to be implemented by you, perhaps using log4net or some other logging utility.

OTHER TIPS

You cannot just call messagebox.write cause you are disconnected from the client. You should register javascript code that shows a messagebox:

this.RegisterClientScriptBlock(typeof(string), "key",  string.Format("alert('{0}');", ex.Message), true);

using MessageBox.Show() would cause a message box to show in the server and stop the thread from processing further request unless the box is closed.

What you can do is,

this.Page.ClientScript.RegisterStartupScript(this.GetType(),"ex","alert('" + ex.Message + "');", true);

this would show the exception in client side, provided the exception is not bubbled.

The way I've done this in the past is to populate something on the page with information when an exception is thrown. MessageBox is for windows forms and cannot be used for web forms. I suppose you could put some javascript on the page to do an alert:

Response.Write("<script>alert('Exception: ')</script>");

I wouldn't think that you would want to show the details of the exception. We had to stop doing this because one of our clients didn't want their users seeing everything that was available in the exception detail. Try displaying a javascript window with some information in it explaining that there has been a problem.

If you want to handle all your error on a single place, you can use the global.asax file (also known as global application file) of your webapplication, and work with the application error event. It goes like this Firts you add the global application file to your project, then on the Application_Error event you put some error handling code, like this:

    void Application_Error(object sender, EventArgs e) 
{
    Exception objErr = Server.GetLastError().GetBaseException();
    string err = "Error Caught in Application_Error event\n" +
            "Error in: " + Request.Url.ToString() +
            "\nError Message:" + objErr.Message.ToString() +
            "\nStack Trace:" + objErr.StackTrace.ToString();
    System.Diagnostics.EventLog.WriteEntry("Sample_WebApp", err, System.Diagnostics.EventLogEntryType.Error);
    Server.ClearError();
    Response.Redirect(string.Format("{0}?exceptionMessage={1}", System.Web.VirtualPathUtility.ToAbsolute("~/ErrorPage.aspx"), objErr.Message));
}

This will log the technical details of your exception into the system event log (if you need to check the error later) Then on your ErrorPage.aspx you capture the exception message from the querystring on the Page_Load event. How to display it is up to you (you can use the javascript alert suggested on the other answers or simple pass the text to a asp.net literal

Hope his helps. Cheers

If you are using .NET Core with MVC and Razor, you have several levels of preprocessing before your page is rendered. Then I suggest that you try wrapping a conditional error message at the top of your view page, like so:

In ViewController.cs:

if (file.Length < 800000)
{
    ViewData["errors"] = "";
}
else
{
    ViewData["errors"] = "File too big. (" + file.Length.ToString() + " bytes)";
}

In View.cshtml:

@if (ViewData["errors"].Equals(""))
{
    @:<p>Everything is fine.</p>
}
else
{
    @:<script>alert('@ViewData["errors"]');</script>
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top