文件异常DRY原理C#

时间:2018-09-27 21:25:27

标签: c# error-handling try-catch dry

在C#中执行许多不同的文件处理时,请始终尝试try catch块,如下所示。有没有一种方法可以将其封装在通用类中,所以我不需要重复自己的DRY。

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

// 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)
{

}

1 个答案:

答案 0 :(得分:1)

您在这里有很多选择。仅提及其中两个:

选项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
}