Search code examples
c++exceptionc++17std-filesystem

How can i return an error to std::filesystem?


For example, this is how I do it using runtime_error

#include <exception>
#include <filesystem>

std::exception &foo(){
    try {
        if(!std::filesystem::is_directory(std::filesystem::path("sdfsdf"))){
            throw std::runtime_error("Error14");
        }
    }
    catch (std::exception &e) {
        return e;
    }
}

int main(){
    foo().what();
    // then i do smth with this error
}

how to do something similar, but with errors returning from std :: filesystem, I mean

std::filesystem::filesystem_error

I have tried this->

#include <filesystem>
std::filesystem::filesystem_error &foo()
{
    try {
        if(!std::filesystem::is_directory(std::filesystem::path("sdfsdf"))){
            throw std::filesystem::filesystem_error("ERROR14", std::error_code());
        }
    }
    catch (std::filesystem::filesystem_error &e) {
         // if (e.code == success)
        {
            return e;
        }
    }
}

int main()
{
    foo();
}

How to return such 'e' if there is no exception(i mean throw)


Solution

  • std::filesystem::is_directory has a few overloads. If you provide an std::error_code object as the last argument it will not throw, but instead set the value of the error code object if an operating system error occurs. So you could use this overload to set the std::error_code object and create the std::filesystem::filesystem_error from it:

    std::filesystem::filesystem_error foo()
    {
        std::error_code err{};
        if (!std::filesystem::is_directory(std::filesystem::path("sdfsdf"), err))
        {
            return std::filesystem::filesystem_error{ "ERROR14", err };
        }
    
        return std::filesystem::filesystem_error{ "SUCCESS", err };
    }
    

    Note that this is returning by value; if you return by reference it will be a reference to a local variable that is destroyed after the function returns, and use of such a dangling reference would lead to undefined behaviour.