user8147504
user8147504

Reputation:

How to make methods automatically covered in try catch blocks

Let say we have something like:

public CustomType DoSomething1() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}

public CustomType DoSomething2() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}

public CustomType DoSomething3() {
   CustomType ct = new CustomType();
   try {
      // do something
   }
   catch(Exception e) {
      ct.Passed = false;
   }
   return ct;
}

These methods are executed by another program using reflection, and if CustomType property Passed == false, program stop executing another. It's due to architecture aspects.

Is it possible to create some attribute or something like that to avoid using try catches, so that if exception is thrown in method it will make Passed property as false and return to program? E.g.

[CatchException('Passed', false)]
public CustomType DoSomething1() {
   CustomType ct = new CustomType();
   // do something
   return ct;
}

And if in process of 'do something' error would be thrown ct.Passed will be equal to 'false'

Upvotes: 1

Views: 178

Answers (2)

InBetween
InBetween

Reputation: 32750

You can do the following:

public static T SafeProcessing<T>(Action<T> action, Action<T> onFail)
    where T: new()
{
     var t = new T();

     try
     {
         a(t);
     }
     catch (Exception e)
     {
          //Log e
          onFail(t);
     }

     return t;
 }

And no you'd use it like this:

return SafeProcessing(c => DoSomething(c), c => c.Safe = false);

Upvotes: 2

Fruchtzwerg
Fruchtzwerg

Reputation: 11389

If I understand your question correct, you want to avoid repeating the try-catch-block. You can solve this by creating a function you are passing the logic you want to deal with.

public static CustomType CatchException(Action a)
{
    CustomType ct = new CustomType();
    try
    {
        a();
    }
    catch
    {
        ct.Passed = false;
    }
    return ct;
}

Now you can simply call the function with any logic you need like multiple times in a very comfortable way.

public CustomType DoSomething1()
{
    return CatchException(() =>
    {
        //Do something
    });
}
...

Upvotes: 0

Related Questions