Search code examples
asp.neterror-handlinghttpcontext

When does HttpContext.AllErrors contain more than one exception?


In an ASP.NET application typical error handling code involves some variation of GetLastError(), however there's also HttpContext.AllErrors collection of which the GetLastError() method only retrieves the first one. What are the scenarios where the AllErrors collection might contain more than 1 exception? I cannot think of anything, but obviously it's there for a purpose...


Solution

  • The ASP.NET Framework supports a different model where a request can encounter multiple errors, all of which can be reported without stopping request processing, allowing for more nuanced and useful information to be presented to the user.

    namespace ErrorHandling
    {
        // sample class adding errors to HttpContext
        public partial class SumControl : System.Web.UI.UserControl
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (IsPostBack)
                {
                    int? first = GetIntValue("first");
                    int? second = GetIntValue("second");
                    if (first.HasValue && second.HasValue)
                    {
                        //result.InnerText = (first.Value + second.Value).ToString();
                        //resultPlaceholder.Visible = true;
                    }
                    else
                    {
                        Context.AddError(new Exception("Cannot perform calculation"));
                    }
                }
            }
    
            private int? GetIntValue(string name)
            {
                int value;
                if (Request[name] == null)
                {
                    Context.AddError(new ArgumentNullException(name));
                    return null;
                }
                else if (!int.TryParse(Request[name], out value))
                {
                    Context.AddError(new ArgumentOutOfRangeException(name));
                    return null;
                }
                return value;
            }
        }
    }
    // intercepting the errors
    public class Global : System.Web.HttpApplication
    {
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            if (Context.AllErrors != null && Context.AllErrors.Length > 1)
            {
                Response.ClearHeaders();
                Response.ClearContent();
                Response.StatusCode = 200;
                Server.Execute("/MultipleErrors.aspx");
                Context.ClearError();
            }
        }
    }
    // MultipleErrors code behind
    public partial class MultipleErrors : System.Web.UI.Page
    {
        public IEnumerable<string> GetErrorMessages()
        {
            return Context.AllErrors.Select(e => e.Message);
        }
    }
    

    The answer is heavily referencing pro asp.net 4.5 from appress