开发者

Design pattern for shared error handling code

开发者 https://www.devze.com 2023-01-06 18:54 出处:网络
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 le

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.

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.

The following pattern occurs frequently, i.e. for every function in the API:

public void CallMethodX(<params>)
{
    try
    {
        API.MethodX(<params);
        <common code for checking for error conditions in API; convert to exceptions and throw>
        <common code for logging API call>
    {
    catch (SEHException xx)
    {
        <common code for querying API for more info on error and creating new managed exception>
    }
}

Also note: the various API methods can have different signatures.

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.

Some thoughts that I've had include:

  • 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].

  • Use the Command pattern. [Would work nicely, but seems a lot of added complexity just to share code]

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.


One solution you could look at is Aspect Oriented Programing. This is the type of problem AOP was designed for. Unfortunitly a lot of langauges do not support AOP well, but if you google for C# Aspect Oriented Programing you will find it is doable see Aspect Oriented Programming Using .Net

0

精彩评论

暂无评论...
验证码 换一张
取 消