C# 中执行使用委托执行代码块 以实现公用try catch

 

C# 中执行使用委托执行代码块 以实现公用try catch

public static T Exec<T>(Func<T> fun)
        {
            T result = default(T);
            try
            {
                result = fun();
            }
            catch
            {
            }
            return result;
        }

        protected static Result ExecResult(Action fun, string funName, string serName = "")
        {
            Result result = new Result();
            try
            {
                fun();
            }
            catch (RunException runE)
            {
                _logger.Info($"{serName}{funName}_runE" + runE.Message);
                result.ErrorCode = runE.ErrorCode;
                result.Msg = runE.Message;
            }
            catch (Exception e)
            {
                _logger.Info($"{serName}{funName}_e" + e.Message);
                _logger.Info($"{serName}{funName}_ST" + e.StackTrace);
                result.ErrorCode = -1;
                result.Msg = e.Message;
            }
            return result;
        }
        public static bool TryExec(Action action, Action<Exception> actionFailed)
        {
            try
            {
                action();
                return true;
            }
            catch (Exception ex)
            {
                // 保存⽇志
                actionFailed(ex);
            }
            return false;
        }


//调用
public Result Test(){

.Result ret = ExecUtilsResult(() =>{

},"测试方法_Test");

return ret;

}

 

posted @ 2022-06-18 17:33  三瑞  阅读(108)  评论(0)    收藏  举报