runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Add a DirectoryPath property to DirectoryNotFoundException to be consistent with FileNotFoundException

Open daiplusplus opened this issue 2 years ago • 14 comments

Background and motivation

The DirectoryNotFoundException type does not provide any way for the thrower to specify the actual directory path in a machine-readable way such that any downstream/consuming program code that catches the exception can isolate the directory-path; currently we're forced to try to parse the human-readable .Message property which, additionally, might be a localized string and thus impossible to reliably process under all circumstances, which is important in error-handling functions.

It's also inconsistent with how FileNotFoundException has a String FileName { get; } property.


I did search through all 7 pages of existing Issues in the runtime repo matching "DirectoryNotFoundException" - none of them are a request to add a directory-path property to the exception.

API Proposal

namespace System.IO;

public class DirectoryNotFoundException : IOException
{
    public DirectoryNotFoundException (string? message, string? directoryPath, Exception? innerException)
        : this(message: message, innerException: innerException)
    {
        this.DirectoryPath = directoryPath;
    }

    public DirectoryNotFoundException (string? message, string? directoryPath)
        : this(message: message)
    {
        this.DirectoryPath = directoryPath;
    }

    public string? DirectoryPath { get; }
}

API Usage


public static void ExampleMethodThatCopiesFilesAround(DirectoryInfo source, DirectoryInfo dest)
{
    if (!source.Exists) throw new DirectoryNotFoundException(message: "Source directory does not exist.", directoryPath: source.FullName);
    if (!dest.Exists) throw new DirectoryNotFoundException(message: "Destination directory does not exist.", directoryPath: dest.FullName);

    foreach (FileInfo fi in source.GetFiles())
    {
        // etc...
    }
}

//

using Microsoft.Extensions.Logging;

public void ConsumingMethodWithLogger()
{
    try
    {
        ExampleMethodThatCopiesFilesAround(source: foo, dest: bar);
    }
    catch (DirectoryNotFoundException dEx)
    {
        using (this.logger.BeginScope("DirectoryPath", dEx.DirectoryPath))
        {
            this.logger.LogError(exception: dEx, message: "Directory not found: {DirectoryPath}", dEx.DirectoryPath);
        }
    }
}

Alternative Designs

No response

Risks

This change involves only adding additional (and entirely optional and nullable) constructor overloads and properties.

It's possible that there exists user-code that subclasses DirectoryNotFoundException to add their own property for the missing directory's full-path, but I assume this wouldn't be an ABI breaking change because user subclasses would still be using a different class member "slot" (right?)

daiplusplus avatar Jun 14 '24 09:06 daiplusplus

Tagging subscribers to this area: @dotnet/area-system-io See info in area-owners.md if you want to be subscribed.

dotnet-policy-service avatar Jun 14 '24 09:06 dotnet-policy-service

There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.

huoyaoyuan avatar Jun 14 '24 09:06 huoyaoyuan

There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.

Right - this DirectoryPath value is entirely optional, for the benefit of users when such a path is available, such as in my example.

It's the same with FileNotFoundException: code that instantiates FileNotFoundException is not required to provide the file-name, but if it's available and the throwing code wants to then it provides a machine-readable way for catch code to get the path, for example, for logging or better error-messages in the UI.

daiplusplus avatar Jun 14 '24 09:06 daiplusplus

There are situations that the directory path can't be determined at all. For example on Windows, trying to open a file from an non-existing directory. The OS error doesn't tell about which level of directory is missing.

@huoyaoyuan the same situation occurs with HttpRequestException where a status code is not always present. In that case, the StatusCode property was made nullable.

Same would apply here.

julealgon avatar Jun 14 '24 13:06 julealgon

Video

  • We discussed making the property non-null but decided it was simpler to just store what we were given
    • Also consistent with FileNotFoundException
  • If message is null but a directoryPath is given Message should return a constructed one, similar to FileNotFoundException
namespace System.IO;

public partial class DirectoryNotFoundException
{
    // Existing ctors
    // public DirectoryNotFoundException();
    // public DirectoryNotFoundException(String);
    // public DirectoryNotFoundException(SerializationInfo, StreamingContext);
    // public DirectoryNotFoundException(String, Exception);
    public DirectoryNotFoundException(string? message, string? directoryPath);
    public DirectoryNotFoundException(string? message, string? directoryPath, Exception? innerException);
    public string? DirectoryPath { get; }
}

terrajobst avatar Aug 13 '24 18:08 terrajobst

If message is null but a directoryPath is given Message should return a constructed one, similar to FileNotFoundException

I did consider that when I wrote-up my initial proposal, but I was wary of the risk of unintentional information disclosure (I understand this is the same reason why KeyNotFoundException doesn't expose the key-that-wasn't-found). But if you're fine with that then I'm fine with that.

daiplusplus avatar Aug 14 '24 08:08 daiplusplus

@terrajobst If message is null but a directoryPath is given Message should return a constructed one, similar to FileNotFoundException

I've started my implementation and hit a minor problem with the .Message generation part: I was modelling my impl off FileNotFoundException - but its .Message string factory ends-up being a call into the CLR via FileLoadException.FormatFileLoadExceptionMessage.

Should I just write my own equivalent message strings in SR then?

daiplusplus avatar Aug 17 '24 11:08 daiplusplus

@jozkee should be able to guide you

terrajobst avatar Aug 30 '24 08:08 terrajobst

Should I just write my own equivalent message strings in SR then?

Yes. Feel free to send a draft PR and we can further discuss the approach.

jozkee avatar Aug 30 '24 16:08 jozkee

Is anybody working on this currently? It seems not and nobody has commented or made any PRs addressing this issue.

I can start working on it if that's okay with you, @jozkee

Flu avatar Jan 06 '25 01:01 Flu

@Flu I completely overlooked @jozkee's reply - I'll find my changes and submit a draft PR soon then. My apologies.

daiplusplus avatar Jan 07 '25 22:01 daiplusplus

Hi! Just checking in since it’s been over a year since the last update. @daiplusplus, are you still planning to submit a draft PR? If not, I would like to pick this up. Of course, happy to step aside if you’re still working on it. Thanks!

ViveliDuCh avatar Mar 06 '26 20:03 ViveliDuCh

go ahead @ViveliDuCh (I was about to assign to copilot!)

danmoseley avatar Mar 18 '26 03:03 danmoseley

(I'm using this as a sample issue for testing an AI workflow. I'm not intending to commit the fix -- unless there ends up being no progress on this for a while again)

danmoseley avatar Mar 28 '26 18:03 danmoseley