Cleanest way to throw an error but not show the user that it has errored (without custom error pages)

StackOverflow https://stackoverflow.com/questions/17750936

  •  03-06-2022
  •  | 
  •  

Question

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.

Was it helpful?

Solution

I recommend Elmah for ASP.NET.

OTHER TIPS

sounds like you want to be notified when there is an error but don't want the user to know about it. you could have the page redirect (if Fatal Error) or finish executing the rest of the file/page after sending you an E-mail or writing to data source that you have access to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top