简体   繁体   中英

Handling error from Async Task in an Async ASP.Net page

I have an async ASP.Net page (Async="true") with code as below.

If an error occurs within the async task method 'DoTask1', then it seems that its not handled by the ASP.Net page framework like other normal errors.

I tried getting Server.GetLastError() in EndAsyncOperation1 method, but it returns a null even when an error occurred in DoTask1 method. Is there some special way to handle errors that occur in an async task?

    protected void btnSave_Click(object sender, EventArgs e)
    {
              PageAsyncTask pagetask1 = new PageAsyncTask(new BeginEventHandler(BeginAsyncOperation1),
                    new EndEventHandler(EndAsyncOperation1),
                    new EndEventHandler(TimeoutAsyncOperation1),
                    new object[] { employeeId, totalEarnings }, true);
                RegisterAsyncTask(pagetask1);
    }

    //Async Task method below is called by the registered task
    private void DoTask1(object[] paras)
    {
            //line below throws an exception on the async task thread
            string x = null;
            string y = x.Trim();
           //More code come here
     }

   IAsyncResult BeginAsyncOperation1(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        task1 = new AsyncTaskDelegate(DoTask1);
        IAsyncResult result = task1.BeginInvoke(state as object[], cb, "task1");
        return result;
    }

   void EndAsyncOperation1(IAsyncResult ar)
    {
        task1.EndInvoke(ar);
        if (success1 == null)
        {
            success1 = true;
        }
    }

    void TimeoutAsyncOperation1(IAsyncResult ar)
    {
        success1 = false;
    }

I finally found the answer to my problem.

One can follow 2 approaches when handling async task error in an ASP.Net page that is flagged with Async = "true". Please note that asyn task method that is called by code in this question is 'DoTask1'.

  • APPROACH 1: Do not enclose anything in try catch, even the code that executes as an async task, as the default ASP.Net error handling will come into play in ASP.Net. So, if your page was posting back as an ajax postback, then the ScriptManager's AsynError event will fire and you can do whatever you like in this event, or if its non-ajax postback then use Page_Error event at the page level to handle the error. Sample code is as given below.

    In my case Server.GetLastError was returning a null since I was clearing the error (ie Server.ClearError) in ScriptManager's AsyncError event.

      protected void radScriptManager_AsyncPostBackError(object sender, System.Web.UI.AsyncPostBackErrorEventArgs e) { //log the exception using ELMAH or any other logging mechanism Exception ex = Server.GetLastError() ; if (ex != null) { Exception bex = ex.GetBaseException(); if (bex != null) { Elmah.ErrorSignal.FromCurrentContext().Raise(bex); } } Server.ClearError(); } 
  • APPROACH 2: The second approach involves putting the call to EndInvoke method in EndAsyncOperation1 within a try catch. The beauty of EndInvoke method is that it re-throws the exception that occurred on the async task method ( ie 'DoTask1'), so we can catch it and handle it as shown in code below. I have used ELMAH to log and handle error in this case, but you could use any logging mechanism.

    There is no need to put the code in the async task method within a try catch when using this second approach, since if an error occurs in async method then it will automatically propagate to the EndInvoke method.

      void EndAsyncOperation1(IAsyncResult ar) { try { task1.EndInvoke(ar); success1 = true; } catch (Exception e1) { success1 = false; //log the exception (this will log error and also send out an error email) Elmah.ErrorSignal.FromCurrentContext().Raise(e1); } if (success1 == null) { success1 = true; } } 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM