How to display an error message in an ASP.NET Web

2020-07-17 04:31发布

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#

3条回答
闹够了就滚
2楼-- · 2020-07-17 05:07

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;
}
查看更多
太酷不给撩
3楼-- · 2020-07-17 05:16

All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.

If occurs during a postback: markup:

<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>

code:

try
{
do something
}

catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
查看更多
SAY GOODBYE
4楼-- · 2020-07-17 05:31

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.

查看更多
登录 后发表回答