“Normal” vs. “error” (control flow) is a fundamental semantic distinction

372 views
Skip to first unread message

Harri L

unread,
May 18, 2022, 12:15:09 PM5/18/22
to golang-nuts
Hi all,

I thought now was the time to go public. The automatic error propagation is possible with the help of a simple Go package, and it has been about three years now:

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()

    w := try.To1(os.Create(dst))
    defer err2.Handle(&err, func() {
        _ = os.Remove(dst)
    })
    defer w.Close()

    try.To1(io.Copy(w, r))
    return nil
}


The playground.

A couple of blog posts about the subject:
I'm the author of those posts and the err2 package. Additional sources for original ideas are mentioned in the blogs and the package documentation. And, of course, pure error values are needed when transporting errors through channels.

I hope that any gopher who tries the err2 package finds it as valuable and productive
as we have. Indeed, Go is one of the most pragmatic and refactor-friendly native languages.

Best regards,
-Harri

Zhaoxun Yan

unread,
May 25, 2022, 7:15:18 AM5/25/22
to golang-nuts
Try & Catch sounds great!

Harri L

unread,
May 30, 2022, 2:37:47 PM5/30/22
to golang-nuts
Thank you!

Indeed, the selected names follow the try/catch idiom, and with the err2, you can write code that includes non-local control flows. I hope that err2 is not confused with exception handling.

The Go2 try-proposal speaks about a helper library needed to get every help that try-macro could offer. The err2 package has that library now, and thanks to generics, the try-API is almost similar to try-macro.

I know many didn't like the try-proposal, but what has been a considerable surprise is how much benefit you get when merging panics and errors.

"Panics. We’ve spent a while trying to harmonize error handling and panics, so that cleanup due to error handling need not be repeated for cleanup due to panics. All our attempts at unifying the two only led to more complexity." 

Then harmonization is now done with err2-package.
Reply all
Reply to author
Forward
0 new messages