Last active
March 15, 2021 10:04
-
-
Save kyleconroy/e48c83425349f2d3954d4e76471ff3f5 to your computer and use it in GitHub Desktop.
Go 2 - Error Handling Proposals
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func CopyFile(src, dst string) error { | |
r, err := os.Open(src) | |
if err != nil { | |
return err | |
} | |
defer r.Close() | |
w, err := os.Create(dst) | |
if err != nil { | |
return err | |
} | |
defer w.Close() | |
if _, err := io.Copy(w, r); err != nil { | |
return err | |
} | |
if err := w.Close(); err != nil { | |
return err | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func CopyFile(src, dst string) error { | |
handle err { | |
return fmt.Errorf("copy %s %s: %v", src, dst, err) | |
} | |
r := check os.Open(src) | |
defer r.Close() | |
w := check os.Create(dst) | |
handle err { | |
w.Close() | |
os.Remove(dst) // (only if a check fails) | |
} | |
check io.Copy(w, r) | |
check w.Close() | |
return nil | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func CopyFile(src, dst string) (err error) { | |
defer func() { | |
if err != nil { | |
err = fmt.Errorf("copy %s %s: %v", src, dst, err) | |
} | |
}() | |
r := try(os.Open(src)) | |
defer r.Close() | |
w := try(s.Create(dst)) | |
try(io.Copy(w, r)) | |
try(w.Close()) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment