ASP.NET C# Catch all exceptions in a class

前端 未结 5 695
我在风中等你
我在风中等你 2021-01-30 12:05

I know this is not the way to do it, and it isn\'t clean at all. I just wonder if it\'s possible.

If I have a class with a bunch of methods

public class          


        
5条回答
  •  清歌不尽
    2021-01-30 12:12

    You could write a higher order function to handle the exceptions, which would make it somewhat cleaner.

    private T FooExceptionHandler(Func function)
    {
       try
       {
          return function();
       }
       catch
       {
          //handle it
       }
    }
    

    You can replace Func with Action if you don't have a return value. You can use it in two ways, outside of the function:

    FooExceptionHandler(MethodA);
    

    or inside each function:

    MethodA()
    {
       return FooExceptionHandler(()=>
          {
             //Function body goes here
          });
    }
    

提交回复
热议问题