为了争论,我假设您的 ICustomObject 有一个属性,以及一个实现它的具体类,如下所示:
public class CustomObject : ICustomObject
{
public string Scope { get; set; }
}
public interface ICustomObject
{
string Scope { get; set; }
}
默认情况下,Exception 类上的 ToString() 方法会递归循环所有 InnerException,以便显示用户可用的所有内容。
如果您想获取该自定义对象的值,您必须做一些稍微不同的事情。
首先,修改您的自定义异常类以接受InnerException 并将其传递给base。
public CompileObjectException(ICustomObject ownerCustomObject, string message, Exception innerException = null)
: base(message, innerException)
{
_ownerCustomObject = ownerCustomObject;
}
然后重写ToString() 方法以循环遍历每个InnerException,并创建一个包含CustomObject 类值的自定义消息:
public override string ToString()
{
return GetInnerException(this);
}
private string GetInnerException(CompileObjectException e)
{
if (e == null)
return "";
return string.Format("{0} ({1}) \n{2}", e.Message, e.OwnerCustomObject.Scope, GetInnerException((CompileObjectException)e.InnerException));
}
现在,当您调用多个嵌套方法时,它们每个都抛出一个异常,您可以保存所有这些异常并将它们显示给用户。
public static void Main()
{
try
{
ParentMethod();
}
catch (Exception e)
{
Console.WriteLine(e); // implicitly calls e.ToString()
}
}
public static void ParentMethod()
{
try
{
ChildMethod();
}
catch (Exception e)
{
throw new CompileObjectException(new CustomObject {Scope = "P"}, "Parent Message", e);
}
}
public static void ChildMethod()
{
try
{
YetAnotherChild();
}
catch (Exception e)
{
throw new CompileObjectException(new CustomObject {Scope = "C"}, "Child Message", e);
}
}
public static void YetAnotherChild()
{
throw new CompileObjectException(new CustomObject {Scope = "C2"}, "Another Child Message");
}
您可能希望针对您的特定情况自定义它,但上面会显示与此类似的链...
Parent Message (P)
Child Message (C)
Another Child Message (C2)