文件异常 DRY 原则 C#



在 C# 中执行许多不同的文件处理时,总是使用 try catch 块,如下图所示。有没有办法将其封装在泛型类中,这样我就不需要重复自己 DRY .

我想简单地尝试捕获,然后在一个足够灵活的类中处理,我可以向其添加处理程序..

// The caller does not have the required permission.
Catch(UnauthorizedAccessException uae)
{
}
// sourceFileName or destFileName is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
// -or- sourceFileName or destFileName specifies a directory.
Catch(ArgumentException ae)
{
}
// sourceFileName or destFileName is null.
Catch(ArgumentNullException ane)
{
}
// The specified path, file name, or both exceed the system-defined maximum length.
Catch(PathTooLongException ptle)
{
}
// The path specified in sourceFileName or destFileName is invalid (for example, it is on an unmapped drive).
Catch(DirectoryNotFoundException dnfe)
{
}
// sourceFileName was not found.
Catch(FileNotFoundException fnfe
{
}
// destFileName exists. -or- An I/O error has occurred.
Catch(IOException ioe)
{
}
// sourceFileName or destFileName is in an invalid format.
Catch(NotSupportedException nse)
{
}

你在这里有很多选择。仅举其中的 2 个:

选项 1:包装器和操作。

public void ProcessFile()
{
ExceptionFilters.CatchFileExceptions( () => {
// .. do your thing
});
}
// somewhere else
public static class ExceptionFilters
{
public static void CatchFileExceptions(Action action)
{
try
{
action();
}
catch(ExceptionTypeA aex)
{
}
// ... and so on
catch(Exception ex)
{
}
}
}

选项 2:使用异常筛选器 此选项实际上将捕获每个异常,除非您还使用筛选器 (C# 6+(

public void ProcessFile()
{
try
{
// do your thing
}
catch(Exception ex)
{
if(!ProcessFileExceptions(ex))
{
throw; // if above hasn't handled exception rethrow
}
}
}
public static void ProcessFileExceptions(Exception ex)
{
if(ex is ArgumentNullException)
{
throw new MyException("message", ex); // convert exception if needed
}
// and so on
return true;
}

在这里,您还可以筛选您感兴趣的异常:

public void ProcessFile()
{
try
{
// do your thing
}
catch(Exception ex) when(IsFileException(ex))
{
if(!ProcessFileExceptions(ex))
{
throw; // if above hasn't converted exception rethrow
}
}
}
public static bool IsFileException(Exception ex)
{
return ex is ArgumentNullException || ex is FileNotFoundException; // .. etc
}

最新更新