Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an error message in an ASP.NET Web Application [duplicate]

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

Duplicate of How to display an error message box in a web application asp.net c#

like image 692
zohair Avatar asked Dec 09 '22 21:12

zohair


2 Answers

Roughly you can do it like that :

try
{
    //do something
}
catch (Exception ex)
{
    string script = "<script>alert('" + ex.Message + "');</script>";
    if (!Page.IsStartupScriptRegistered("myErrorScript"))
    {
         Page.ClientScript.RegisterStartupScript("myErrorScript", script);
    }
}

But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.

like image 185
Canavar Avatar answered Dec 12 '22 10:12

Canavar


The errors in ASP.Net are saved on the Server.GetLastError property,

Or i would put a label on the asp.net page for displaying the error.

try
{
    do something
}
catch (YourException ex)
{
    errorLabel.Text = ex.Message;
    errorLabel.Visible = true;
}
like image 23
Jhonny D. Cano -Leftware- Avatar answered Dec 12 '22 11:12

Jhonny D. Cano -Leftware-