<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%--AllowCustomErrorsRedirect属性设置为false,配合后台的自定义错误使用--%> <asp:ScriptManager ID="ScriptManager1" runat="server" AllowCustomErrorsRedirect="false" OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel> <%--自定义错误处理--%> <div id="error"></div> <script type="text/javascript" language="javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, e) { e.set_errorHandled(true); //将信息显示到上面的div区块中innerHTML,这里可以设置默认的错误信息 $get("error").innerHTML = "Sorry, an error has occurred: " + e.get_error().message; setTimeout(function(){ $get("error").innerHTML = ""; }, 3000);//3秒后变为空 }); </script> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication4 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //自定义错误处理,配合web.config文件中的错误配置节点customErrors(设置为on的时候才生效,同时还要制定错误页)和AllowCustomErrorsRedirect(是否允许customErrors)使用 throw new Exception("错误信息提示!"); } protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { ScriptManager.GetCurrent(this).AsyncPostBackErrorMessage = e.Exception.Message; } } }