2010-12-01 8 views
1

Dans Silverlight, j'utilise lambdas pour la récupération de données à partir de mon service (dans cet exemple, un service de données WCF). Les exceptions à l'intérieur du rappel sont englouties par le système à moins que je ne les manipule avec un essai. Par exemple:Gestion des exceptions dans Silverlight Appels lambda asynchrones

this.Context.BeginSaveChanges(() => 
{ 
    // throwing an exception is lost and the Application_UnhandledException doesn't catch it 

}, null); 

j'ai une fonction d'assistance pour connecter l'exception et rediriger vers une page ASPX d'erreur générale, mais je dois envelopper tout lambdas avec try/prises qui est ok, si je dois faire mais y a-t-il un meilleur moyen?

Répondre

2

Vous pouvez créer un ensemble de méthodes d'aide pour envelopper le lambda est avec: - sans se soucier de défaut boilerplate la gestion des exceptions de

public static class Helper 
{ 
    public static AsyncCallback GetAsyncCallback(Action<IAsyncResult> inner) 
    { 
     return (a) => 
     { 
      try 
      { 
       inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
    } 

    public static Action GetAction(Action inner) 
     { 
     return() => 
     { 
      try 
      { 
       inner(); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 

     public static Action<T> GetAction(Action<T> inner) 
     { 
     return (a) => 
     { 
      try 
      { 
       inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
     // and so on also:- 

     public static Func<T> GetFunc(Func<T> inner;) 
     { 
     return() => 
     { 
      try 
      { 
       return inner(); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
     public static Func<T1, TReturn> GetFunc(Func<T1, TReturn> inner;) 
     { 
     return (a) => 
     { 
      try 
      { 
       return inner(a); 
      } 
      catch (Exception err) 
      { 
       // Your handling for "uncaught" errors 
      } 
     }; 
     } 
} 

Maintenant, vous pouvez envelopper lambda: -

this.Context.BeginSaveChanges(Helper.GetAsyncCallback((ar) =>    
{    
    // Only needs specific exception handling or none at all    

}), null);