I'm running some code that only has to run once but it depends on external resources and may fail. I want the error to appear in the event log but I do not want the user to see it. I'd like to avoid using custom error pages if possible.
I could catch the exception and write it to the event log myself but I'm concerned that I can't guarantee what the name of the asp.net event source would be (it appears to change depending on the framework version.) I also can't create my own event source since that requires administrative permissions.
The approach that I'm currently working towards is a bit of a hack (which doesn't work yet) and it looks like this:
public void Init(HttpApplication context)
{
try
{
throw new Exception("test"); // This is where the code that errors would go
}
catch (Exception ex)
{
HttpContext.Current.Application.Add("CompilationFailed", ex);
}
}
private void context_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Application.AllKeys.Contains("CompilationFailed"))
{
// It failed on Init - we can't throw an exception there so lets try it here
var origEx = (Exception)HttpContext.Current.Application["CompilationFailed"];
// Only ever do this once
HttpContext.Current.Application.Remove("CompilationFailed");
// This should just look like a normal page load to the user
// - it will be the first request to the site so we won't be
// interrupting any postbacks or anything
HttpContext.Current.Response.AddHeader("Location", "/");
HttpContext.Current.Response.StatusCode = 301;
try
{
HttpContext.Current.Response.End();
}
catch (ThreadAbortException ex)
{
throw origEx;
}
}
}
Ideally what I would really like is a RecordException() method within IIS if anything like that exists.
The defaultRedirect attribute is optional. If provided, it specifies the URL of the custom error page and indicates that the custom error page should be shown instead of the Runtime Error YSOD. The mode attribute is required and accepts one of three values: On , Off , or RemoteOnly .
Steps for Custom Error PageCreate a separate folder for Error. Add Web Form for custom error page. Set <customErrors> setting in Web. Config file of the application.
To display a custom error page with an appropriate error code, use the <httpErrors> section only, and do not use the <customErrors> section.
You can handle default errors and HTTP errors by adding a customErrors section to the Web. config file. The customErrors section allows you to specify a default page that users will be redirected to when an error occurs.
I recommend Elmah for ASP.NET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With