devKoen1
devKoen1

Reputation: 179

Run a method every time a try catch is used in ASP.NET

I was wondering if it's possible to write code that runs everytime a try catch block is used in ASP.NET without having to add any attribute to the method or code inside a try catch block. By that I mean one piece of code for all of the try catches in an entire project. Would it be possible to customize try catch or to invoke a method everytime a try catch is used? Thanks in advance

Upvotes: 0

Views: 373

Answers (2)

RandomUs1r
RandomUs1r

Reputation: 4190

What you're looking for is finally:

try {}
catch(Exception ex)
{}
finally {
//Code executes after try catch regardless of outcome
}

What you're really looking for:

   public class GlobalExceptionLogger : ExceptionLogger
    {
        public override void Log(ExceptionLoggerContext context)
        {
            //elmah logging code for context.exception
        }
    }

Upvotes: 1

Artem
Artem

Reputation: 2314

You can write your own try-catch, like the following:

public static class Try
{
    public static void Action(Action a)
    {
        try
        {
            a();
        }
        catch (Exception e)
        {
            //do whatever you want here
            throw new OtherException(e.Message, e);
        }
    }
}

And use it everywhere in your project:

Try.Action(() => 
// code to be wrapped with try
));

Upvotes: 0

Related Questions