Suppose I have a function that starts by creating a directory, and then doing some more stuff, like this:
{
err := os.Mkdir(path, os.ModePerm)
...
err = doSomething()
if err != nil {
return nil, err
}
err = doSomethingElse()
if err != nil {
return nil, err
}
return path, nil
}
Now, I want the function to delete the directory it created in all of those cases where an error occured. What is the cleanest way to do this?
One way would be to call os.RemoveAll
in every if
branch, but that's not a very nice solution. Another way would be to use a defer
statement, but that would also get executed in the case where there was no error.