这不是什么大问题,而是更多的反馈和想法。我一直在考虑通过我们的内部团队彻底测试过的方法的实现。我想编写一个通用的异常捕获方法和报告服务。
我认为这不像“try-catch”块那么容易,但允许使用统一的方法来捕获异常。理想情况下,我想执行一个方法,提供一个失败回调并记录调用方法的所有参数。
通用尝试执行。
public class ExceptionHelper
{
public static T TryExecute<T, TArgs>(Func<TArgs, T> Method, Func<TArgs, T> FailureCallBack, TArgs Args)
{
try
{
return Method(Args);
}
catch (Exception ex)
{
StackTrace stackTrace = new StackTrace();
string method = "Unknown Method";
if (stackTrace != null && stackTrace.FrameCount > 0)
{
var methodInfo = stackTrace.GetFrame(1).GetMethod();
if (methodInfo != null)
method = string.Join(".", methodInfo.ReflectedType.Namespace, methodInfo.ReflectedType.Name, methodInfo.Name);
}
List<string> aStr = new List<string>();
foreach (var prop in typeof(TArgs).GetProperties().Where(x => x.CanRead && x.CanWrite))
{
object propVal = null;
try
{
propVal = prop.GetValue(Args, null);
}
catch
{
propVal = string.Empty;
}
aStr.Add(string.Format("{0}:{1}", prop.Name, propVal.ToString()));
}
string failureString = string.Format("The method '{0}' failed. {1}", method, string.Join(", ", aStr));
//TODO: Log To Internal error system
try
{
return FailureCallBack(Args);
}
catch
{
return default(T);
}
}
}
}
我所知道的退路。
- 使用反射的性能损失
- MethodBase(methodInfo)可能无法通过优化获得
- 错误处理程序周围的 try-catch。基本上,我可以使用 TryExecute 包装器来围绕错误回调进行 try-catch,但这可能会导致堆栈溢出情况。
这是一个示例实现
var model = new { ModelA = "A", ModelB = "B" };
return ExceptionHelper.TryExecute((Model) =>
{
throw new Exception("Testing exception handler");
},
(Model) =>
{
return false;
},
model);
想法和评论表示赞赏。