I have web application in asp.net. I have to implement custom error page. Means if any eror occurs(runtime). I have to display exception and stacktrace on errorpage.aspx shall i handle from master page or on page level and how.
<customErrors mode="On" defaultRedirect="~/Error_Page.aspx"></customErrors>
You can handle it in global.asax :
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = System.Web.HttpContext.Current.Error;
//Use here
System.Web.HttpContext.Current.ClearError();
//Write custom error page in response
System.Web.HttpContext.Current.Response.Write(customErrorPageContent);
System.Web.HttpContext.Current.Response.StatusCode = 500;
}
Please do not use Redirection as a means of displaying error messages, because it breaks HTTP. In case of an error, it makes sense for the server to return an appropriate 4xx or 5xx response, and not a 301 Redirection to a 200 OK response. I don't know why Microsoft added this option to ASP.NET's Custom Error Page feature, but fortunately you don't need to use it.
I recommend using IIS Manager to generate your web.config file for you. As for handling the error, open your Global.asax.cs
file and add a method for Application_Error
, then call Server.GetLastError()
from within.
Use Elmah dll for displaying your error with nice UI. You can maintain log using this DLL.
In the Global.asax
void Application_Error(object sender, EventArgs e)
{
Session["error"] = Server.GetLastError().InnerException;
}
void Session_Start(object sender, EventArgs e)
{
Session["error"] = null;
}
In the Error_Page Page_Load event
if (Session["error"] != null)
{
// You have the error, do what you want
}
You can access the error using Server.GetLastError;
var exception = Server.GetLastError();
if (exception != null)
{
//Display Information here
}
For more information : HttpServerUtility.GetLastError Method
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.