我试图通过将类型封装在TypeInitializationException中来管理实例化类型时抛出的各种类型的异常。为了避免重复代码,我在工厂里有这个:
try
{
CheckFields(field1, field2...);
}
catch (Exception ex) when (ex is ArgumentException || ex is ArgumentNullException || ex is ArgumentOutOfRangeException)
{
throw new TypeInitializationException("MyType", ex);
}
....
private void CheckFields(string field1, string field...)
{
if (field1== null) throw new ArgumentNullException("field1", "field1 can't be null");
if (field1.Trim().Length==0) throw new ArgumentException("field1 can't be empty", "field1");
if (field1.Trim().Length > 35) throw new ArgumentOutOfRangeException("field1", "field1 can't be longer than 35 characters");
if (field2== null) throw new ArgumentNullException("field2", "field2 can't be null");
if (field2.Trim().Length == 0) throw new ArgumentException("field2 can't be empty", "field2");
if (field2.Trim().Length > 35) throw new ArgumentOutOfRangeException("field2", "field2 can't be longer than 35 characters");
....
}
稍后捕获TypeInitializationException时,我只需要读取内部异常。
我的问题是内部异常被封装为异常,而不是封装 ArgumentException,ArgumentNullException或ArgumentOutOfRangeException。我可以' GetType()'之后的InnerException它看到什么是真正的类型,并投下它,但我想抛出原始类型的异常。到目前为止我唯一的解决方案是:
catch (Exception ex) when (ex is ArgumentException || ex is ArgumentNullException || ex is ArgumentOutOfRangeException)
{
if (ex is ArgumentException) throw new TypeInitializationException("MyType", (ArgumentException)ex);
if (ex is ArgumentNullException) throw new TypeInitializationException("MyType", (ArgumentNullException)ex);
if (ex is ArgumentOutOfRangeException) throw new TypeInitializationException("MyType", (ArgumentOutOfRangeException)ex);
}
有更轻松/更优雅的方式吗?