Raf*_*ski 2 .net c# exception-handling exception
就像问题一样.我想检查异常集合上的某些内容是否是我的自定义异常,还是由.Net框架提供的Exception类.提前为您提供帮助.\
请注意:
我不知道我的自定义异常的类名是什么,它可以被称为exceptionA,exceptionB或者例如xyzException
我有这样的代码:
public IEnumerable<Type> GetClassHierarchy(Type type)
{
if (type == null) yield break;
Type typeInHierarchy = type;
do
{
yield return typeInHierarchy;
typeInHierarchy = typeInHierarchy.BaseType;
}
while (typeInHierarchy != null && !typeInHierarchy.IsInterface);
}
public string GetException(System.Exception ex)
{
if (ex == null)
{
return null;
}
if (ex.InnerException == null)
{
return ex.Message;
}
var exceptionHerarchy = GetClassHierarchy(ex.GetType());
var isMyException = exceptionHerarchy.Any(t => t != typeof(System.Exception));
if (isMyException)
{
return string.Format("{0};{1}", ex.Message, GetException(ex.InnerException));
}
else
{
return GetException(ex.InnerException);
}
}
Run Code Online (Sandbox Code Playgroud)
var isMyException = exceptionHerarchy.Any(t => t!= typeof(System.Exception)); 这是alays返回true,因为列表中可能存在此类型
非常简单:
var t = myException.GetType().FullName;
bool isSystemException = (t.StartsWith("System."));
Run Code Online (Sandbox Code Playgroud)
.NET Framework中的异常类型都在System其子名称空间中或其中一个.
编辑:为了使这个稍微漂亮,为Exception类创建一个扩展函数:
public static bool IsSystemException(this Exception exception)
{
return (exception.GetType().FullName.StartsWith("System."));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1413 次 |
| 最近记录: |