开发者

How to handle exceptions that are deep in code?

开发者 https://www.devze.com 2023-04-02 18:35 出处:网络
I have a webservice that returns xml.The problem is methods that are executed \"deep\" in code where a simple return won\'t stop program execution.

I have a webservice that returns xml.The problem is methods that are executed "deep" in code where a simple return won't stop program execution.

What happens is I set my xml error message in a catch statement but the code will keep executing through the rest of the outer method and overwrite my xml error response.

Is there a design pattern or best practice to get around this?

      Main Program Block                    SomeClass

         execute someMethod()     ---->     public someMethod()
                                            {
                                                    -----> private method()// try / catch error occurred (send back an xml error response)

                                                    // code execution continues and does some stuff and generates an xml response
                                 开发者_StackOverflow社区                   <request>
                                                    <success>true</success>
                                                    </request>
                                            }


catch (Exception)
{
    // Set errors here
    throw;
}

This will rethrow the exception. Is that what you're looking for?


You can re-throw the exception. For example:

    private static string errorMessage;
    static void Main(string[] args)
    {
        try
        {
            Test1();
        }
        catch (Exception ex) 
        {
            Console.WriteLine("Something went wrong deep in the bowels of this application! " + errorMessage );
        }

    }

    static void Test1()
    {
        try
        {
            Test2(1);
            Test2(0);   
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            throw;
        }
    }

    static string Test2(int x)
    {
        if (x==0) throw new ArgumentException("X is 0!");
        return x.ToString();
    }

An additional piece of advice: When re-throwing an exception, use throw;, not throw ex;, in order to preserve the stack trace. See this for some more information on the subject.


You need to consider setting up Exception boundaries within your architecture.

I've used Microsoft's Exception Handling Block successfully in the past to do this.

This will allow you to set up different policies for dealing with and propagating exceptions as shown in the diagram below;

It will help you deal with scenarios such as;

  • Logging
  • Replacing
  • Wrapping
  • Propagating
  • User friendly messages

How to handle exceptions that are deep in code?

It's worth a look depending on how far you want to take your exception handling.


It's generally wise to catch your exceptions as far up the chain as possible. So it would be the main service method's responsibility to catch different types of exceptions and determine the appropriate response. Deep-down code should not just "swallow" the exception unless it really knows how to handle it and move on gracefully.

If you want to make it so certain exceptions can tell the upper-level code that it's supposed to use specific information for the response, you can create a custom exception type with properties that the exception-catching code in the service method can check.

// In your deep down code
catch (Exception e)
{
    throw new ReturnErrorMessageException("The user should see this message.", e);
}
// In your service method
catch (SendErrorMessageException e)
{
    Response.Message = e.UserFacingErrorMessage;
    _logger.LogError("An error occurred in the web service...", e);
}


Probably the best solution for what you are looking for is to use Aspect Oriented Programming (AOP) and create an Exception handling Aspect(s) that catches and handles all the exceptions then you check for exceptions at the service level.

The advantage of this is it removes the try catch from your code and enables you to handle the exceptions in the a modular manner.

Some AOP solutions for .NET include Castle Windsor, Spring.NET and Microsoft Unity.

0

精彩评论

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

关注公众号