Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to wrap every WCF call in a try-catch block
    primarykey
    data
    text
    <p>I have a website where I need to make asynchronous calls to a WCF service. I want to wrap each call in a try-catch block so I can deal with TimeoutExceptions and CommunicationExceptions. </p> <p>However, I don't want to just copy-paste the exact same try-catch block every time I make a call to my service. Is there some way I can use delegates to only write the try-catch block once? I also still want to capture the exception messages.</p> <p>I want to call it like:</p> <pre><code>// This method returns void TryCatchHelper(x =&gt; x.WCFMethod1(param1, param2)); // This method has a return value but no params var returnValue = TryCatchHelper(x =&gt; x.WCFMethod2()); </code></pre> <p>EDIT: Here's what my code looks like now:</p> <pre><code>User GetUser(int Id) { User returnUser = null; try { // Open WCF channel, etc. returnUser = myWCFClient.GetUser(Id); } catch (TimeoutException exception) { Log(exception.Message); // Abort WCF factory } catch (CommunicationException exception) { Log(exception.Message); // Abort WCF factory } return returnUser; } </code></pre> <p>I don't want to use this same try-catch block in every single method I set up in my repository. I tried doing something like this, but it gave me an error on the params. I know I'm not using them correctly, but I need a way to define a delegate that can stand in for all of the WCF method calls I want to make:</p> <pre><code>delegate object WCFAction(params object[] parameters); object DoWCFAction(WCFAction action, params object[] parameters) { object returnValue = null; try { // Open WCF channel, etc. returnValue = action(parameters); } catch (TimeoutException exception) { Log(exception.Message); // Abort WCF factory } catch (CommunicationException exception) { Log(exception.Message); // Abort WCF factory } return returnValue; } void MainMethod() { // Compiler error User user = DoWCFAction(GetUser, 1); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload