domingo, 25 de noviembre de 2012

Response.Redirect() - "Thread was being aborted" (Subproceso anulado)

Este error se produce cuando Response.Redirect() se encuentra dentro de un bloque try/catch, interrumpiendo el hilo actual y produciendo la excepción.



Ej:
-C#-
protected void nombreFuncion()
    {
        nNegocio nObj = new nNegocio();
        try
        {
            nObj.Delete(Convert.ToInt32(Request.QueryString["ID"]));
            Response.Redirect("url.aspx?Confirm=OK");
        }
        catch (Exception)
        {

            Response.Redirect("url.aspx?Confirm=Error");
         
        }
    }

-VB.NET-

Protected Function nombreFuncion()
  Dim nObj As New nNegocio
  Try

           nObj.Delete(Convert.ToInt32(Request.QueryString("ID")))
            Response.Redirect("url.aspx?Confirm=OK")

  Catch (Exception)
        Response.Redirect("url.aspx?Confirm=Error")
  End Try
End Function

//Solución:
  La solución más sencilla sería sacar el Response.Redirect() del manejo de excepciones(try/catch).
En mi caso voy a utilizar una variable booleana. Sería algo así:

-C#-
protected void nombreFuncion()
    {
       bool flag = true;
        nNegocio nObj = new nNegocio();
        try
        {
            nObj.Delete(Convert.ToInt32(Request.QueryString["ID"]));
            flag = true;
        }
        catch (Exception)
        {

           flag = false;
         
        }

         //Pregunto por la variable bool.
         if(flag)
         {
               Response.Redirect("url.aspx?Confirm=OK");
         }
         else
         {
               Response.Redirect("url.aspx?Confirm=Error");
         }
    }

-VB.NET-

Protected Function nombreFuncion()
  Dim flag As Boolean = True
  Dim nObj As New nNegocio
  Try

           nObj.Delete(Convert.ToInt32(Request.QueryString("ID")))
           flag = True

   Catch (Exception)
        flag = False
   EndTry

   //Pregunto por la variable bool.
   If flag Then
    Response.Redirect("url.aspx?Confirm=OK")
  Else
    Response.Redirect("url.aspx?Confirm=Error")
  End If
End Function

No hay comentarios:

Publicar un comentario