Error communication and recovery approaches in .NET

后端 未结 3 1699
青春惊慌失措
青春惊慌失措 2021-01-16 06:53

I am trying to do error communication and recovery in my C# code without using Exceptions. To give an example, suppose there is a Func A, which can be called by Func B or Fu

3条回答
  •  遥遥无期
    2021-01-16 07:25

    How about a common FunctionResult object that you use as an out param on all your methods that you don't want to throw exceptions in?

    public class FuncResultInfo
        {
            public bool ExecutionSuccess { get; set; }
            public string ErrorCode { get; set; }
            public ErrorEnum Error { get; set; }
            public string CustomErrorMessage { get; set; }
    
            public FuncResultInfo()
            {
                this.ExecutionSuccess = true;
            }
    
            public enum ErrorEnum
            {
                ErrorFoo,
                ErrorBar,
            }
        }
    
        public static class Factory
        {
            public static int GetNewestItemId(out FuncResultInfo funcResInfo)
            {
                var i = 0;
                funcResInfo = new FuncResultInfo();
    
                if (true) // whatever you are doing to decide if the function fails
                {
                    funcResInfo.Error = FuncResultInfo.ErrorEnum.ErrorFoo;
                    funcResInfo.ErrorCode = "234";
                    funcResInfo.CustomErrorMessage = "Er mah gawds, it done blewed up!";
                }
                else
                {
                    i = 5; // whatever.
                }
    
                return i;
            }
        }
    

    Make sure all of your functions that can fail without exceptions have that out param for FuncResultInfo

提交回复
热议问题