Home > Software design >  How to handle "no such file or directory" in os.Stat
How to handle "no such file or directory" in os.Stat

Time:01-26

I have a piece of code that is looking to stat a file and return some default values if the file does not exist. Namely, the piece of code looks something like the following:

fileInfo, err := os.Stat(absolutePath)
if err != nil {
    if os.IsNotExist(err) {
        return <default val>, nil
    }
    return nil, fmt.Errorf(...)
}

To "catch" the "file does not exist" error I have read that it's advised to use os.IsNotExist to check if the error indicates the file does not exist. However, os.IsNotExist does not catch this error since the platform returns open <blah>: no such file or directory. I can add my own error handling here but is there is an idiomatic way to handle "file does not exist" errors from os calls? It seems like the error handled by the os.IsNotExist check is special cased to just one type of potential "file does not exist" error.

CodePudding user response:

If you read the documentation, you'll see this:

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist). [emph. mine]

  • Related