文件异常DRY原理C#

File Exceptions DRY principle C#

在 C# 中执行大量不同的文件处理时,始终使用如下所示的 try catch 块。有没有办法将它封装在一个通用的 class 中,这样我就不需要重复 DRY 了。

我想简单地尝试 catch 然后在一个 class 中处理,它足够灵活,我可以向它添加处理程序..

// 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
}