gpt4 book ai didi

c# - 处理(记录)自定义异常的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 20:30:22 24 4
gpt4 key购买 nike

方法尝试记录自定义异常(自定义异常类作为代码示例)的情况会导致问题:

[Serializable]
public class CustomException : Exception
{
public CustomException() { }
public CustomException(string message) : base(message) { }
public CustomException(string message, Exception inner) : base(message, inner) { }
protected CustomException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}

创建异常:

CustomException ex = new CustomException("Here is a new custom exception! ");
LogError(ex);

记录异常的方法(自定义和其他!):

public static void LogError(Exception ex)
{
//Saving exception messages, inner exceptions etc
//...
}

在这种情况下,自定义异常的 ex.Stacktrace 在记录时为空!

我认为原因是日志记录方法(试图成为通用方法)将 Exception 对象作为参数而不是 CustomException (?)。创建日志记录方法的正确方法是什么,因为用不同的异常类型重载它似乎有点违反直觉?

最佳答案

I believe the reason is that the logging method (which tries to be a general purpose method) takes a Exception object as parameter rather than CustomException (?)

不正确。它为空,因为您实际上并没有抛出异常,只是创建了它。

堆栈跟踪是在异常沿调用堆栈向上移动时生成的。在捕获异常时以相同的方法抛出异常只会创建一个堆栈跟踪项。

关于c# - 处理(记录)自定义异常的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com