batsta13
batsta13

Reputation: 539

Streamlining Exception Handling

I'm creating an asp.net site that populates a database. My goal is to print success/fail messages for each database operation. Currently I have try catch statements for each drop, insert and create statement. My question is: can I create a single method that performs exception handling where it is passed a method call e.g:

public void doWork()
{
  if(exceptionHandling(calculateStuff()) != null)
  {
    div.innerHTML += "there was a problem (print error)";
  }
}

public Exception exceptionHandling(methodCall)
{
  try {
   //execute method call
   calculateStuff();
  }

  catch(Exception error)
  {
    return error;
  }

  public void calculateStuff()
  {
    //calcuate stuff here
  }
}

My aim is to reduce repetition in my code by reducing the number of try/catch statement. Is the above an acceptable way of doing it or is there a better way?

Upvotes: 3

Views: 211

Answers (2)

Neel
Neel

Reputation: 11721

You can definatly do it and my suggestion would be to use Postsharp which you can download from nugget and it works like a charm ..For example have a look at below code

/// <summary> 
/// Aspect that, when applied on a method, catches all its exceptions, 
/// assign them a GUID, log them, and replace them by an <see cref="InternalException"/>. 
/// </summary> 
[Serializable] 
public class ExceptionPolicyAttribute : OnExceptionAspect 
{ 
    /// <summary> 
    /// Method invoked upon failure of the method to which the current 
    /// aspect is applied. 
    /// </summary> 
    /// <param name="args">Information about the method being executed.</param> 
  public override void OnException(MethodExecutionArgs args) 
    { 
        Guid guid = Guid.NewGuid(); 

        Trace.TraceError("Exception {0} handled by ExceptionPolicyAttribute: {1}", 
            guid, args.Exception.ToString()); 

        throw new InternalException( 
            string.Format("An internal exception has occurred. Use the id {0} " + 
            "for further reference to this issue.", guid)); 
    } 
} 

and to use this just put attribute on ur method as below :-

[ExceptionPolicy]
public void doWork()
{
  ///Your code
}

so whenever error will occure in dowork it will redirect to piece of code for exception handling.

For more information :-

http://www.postsharp.net/blog/post/Day-6-Your-code-after-PostSharp

Upvotes: 1

decPL
decPL

Reputation: 5402

You can always do the following (I've modified your code slightly that it no longer returns an Exception, but instead the calling code provides the code to call on exception; it's a question of readability for me, you can hopefully modify this if you prefer your approach):

public void SomeOperation(MyObject param)
{
   //do something
}

public void SomeOtherOperation(AnotherObject param)
{
   //do something else
}

public void SafelyExecute<TParam>(Action<TParam> methodToExecute,
                                  Action<Exception> exceptionHandler,
                                  TParam param)
{
    try
    {
        methodToExecute(param);
    }
    catch (Exception e)
    {
        exceptionHandler(e);
    }
}

public void DoWork()
{
   SafelyExecute(SomeOperation,
                 e => div.innerHTML += "there was a problem" + e.Message,
                 myObjectInstance);
   SafelyExecute(SomeOtherOperation,
                 e => div.innerHTML += "there was a different problem" + e.Message,
                 anotherObjectInstance);
}

Upvotes: 1

Related Questions