-
I don't understand why the example CopyFile code places func CopyFile(src, dst string) (err error) {
defer err2.Returnf(&err, "copy %s %s", src, dst)
r := try.To1(os.Open(src))
defer r.Close()
defer err2.Handle(&err, func() {
fmt.Println("handled os.Remove")
err = fmt.Errorf("wrapped %w", err)
_ = os.Remove(dst)
})
w := try.To1(os.Create(dst))
defer w.Close()
try.To1(io.Copy(w, r))
return nil
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Great question! Sorry for my late reply. I was traveling this week. Short answer: The To be sure, I wanted to test the
ERR: copy main.go main.bak: open main.bak: permission denied Where the main function was: func main() {
defer err2.Catch(func(err error) {
fmt.Println("ERR:", err)
})
try.To(CopyFile("main.go", "main.bak"))
} Unfortunately, I couldn't figure out fastly enough of another way to simulate the cleaning target file
ERR: copy main.go main.bak2: cannot write file Where the used mocked func errCopy(w io.Writer, r io.Reader) (n int64, err error) {
return 0, fmt.Errorf("cannot write file")
} And printing the 'cleaning the target' added to I hope this helps. Please note that you can change the first |
Beta Was this translation helpful? Give feedback.
-
Sorry, you are right, the original proposal is doing things that way. IMHO it's not optimal: |
Beta Was this translation helpful? Give feedback.
Great question! Sorry for my late reply. I was traveling this week.
Short answer: The
err2.Handle
withos.Remove
is after theos.Create
because it's needed only ifio.Copy
fails. I suppose the cleaning overall exists because the original authors ofCopyFile
wanted to show how error handling can have parts where resource cleanup is necessary. FYI, all theerr2
handlers are called if they exist in the current defer stack at the moment whenerr != nil
. Those handlers are:err2.Annotex
,err2.Returnx
anderr2.Handle
.To be sure, I wanted to test the
CopyFile
in the current err2 Go documentation. These are the results, and it seems to work as meant to: