title: Design pattern for shared error handling code
body: <p>I'm looking for some thoughts/opinions on architecture for a layer of code that invokes methods in an API.  In my case, the calling code is C#/.NET and the API is part of an unmanaged legacy DLL.  But the same question could apply in many different languages/environments.</p>
  
  <p>I'm basically writing a managed wrapper around an unmanaged API.  The wrapper exists to handle marshaling to the unmanaged code and to convert lower-level errors and exceptions to managed exceptions.</p>
  
  <p>The following pattern occurs frequently, i.e. for every function in the API:</p>
  
  <pre><code>public void CallMethodX(&lt;params&gt;)
  {
      try
      {
          API.MethodX(&lt;params);
          &lt;common code for checking for error conditions in API; convert to exceptions and throw&gt;
          &lt;common code for logging API call&gt;
      {
      catch (SEHException xx)
      {
          &lt;common code for querying API for more info on error and creating new managed exception&gt;
      }
  }
  </code></pre>
  
  <p>Also note: the various API methods can have different signatures.</p>
  
  <p>The basic question is: what do people recommend for abstracting out the common code for logging and error handling.  Even in the best case, i.e. by moving common code into static utility functions, there is a lot of repeated boilerplate code around each API method invocation.</p>
  
  <p>Some thoughts that I've had include:</p>
  
  <ul>
  <li><p>Moving common code into utility class that accepts a delegate for the actual method and injecting the delegate into the utility class.  The utility class then does the actual exception handling and logging.  [Works fine, but creating/passing delegate gets a little clumsy/ugly].</p></li>
  <li><p>Use the Command pattern.  [Would work nicely, but seems a lot of added complexity just to share code]</p></li>
  </ul>
  
  <p>Any other thoughts?  Best OO practices for where to put common exception handling code?  Note that I do not want to put handler code higher up the call stack, i.e. locate it with the client that calls my layer--since that layer should be completely decoupled from the details of querying API for detailed error info and converting to managed exceptions.</p>