Generic error handling with panic, recover, and defer

485 views
Skip to first unread message

Marcos César de Oliveira

unread,
Sep 21, 2021, 4:57:38 PM9/21/21
to golang-nuts
With go 1.18 generics implementation it is now possible to provide error handling functions in a fashion similar to the "try" proposal. I wrote a small library that implements this approach: https://github.com/mcesar/must.

An example of usage is as follows:

package main
import (
    "fmt"
    "os"
)
func main() {
    fmt.Println(f())
}
func f() (err error) {
    defer must.Handle(&err)
    f := must.Do(os.Open("file"))
    defer f.Close()
    // ...
    return nil
}

This idea is not new, but I think it is worthwhile to have an implementation to experiment with.

Nathaniel Lehrer

unread,
Jul 29, 2022, 6:01:28 PM7/29/22
to golang-nuts
Hi mcesar, thanks for putting this together! I'm thinking about using this for our project...

Curious if anyone would like to share their experience employing this library?

Nathaniel Lehrer

unread,
Jul 29, 2022, 6:02:16 PM7/29/22
to golang-nuts
This is similar, maybe this one is better to use? https://github.com/lainio/err2

On Tuesday, September 21, 2021 at 1:57:38 PM UTC-7 mces...@gmail.com wrote:

Sean Liao

unread,
Jul 29, 2022, 6:22:01 PM7/29/22
to golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4e492605-7922-4155-9efc-5521a9ecc6e4n%40googlegroups.com.

Harri L

unread,
Aug 6, 2022, 5:35:23 AM8/6/22
to golang-nuts
Thanks for mentioning https://github.com/lainio/err2. I'm the author of the package. Maybe a few words about it would be ok.

We could say that the err2 package is one of the most important libraries in our corporation's use. It's over three years old by now, and we have used it both for internal and open source projects: small and large, and, of course, in production as well. So, we take it quite seriously.

The idea and need for the package came from the famous: "more error handling with less checking." You can read my blog post about some of the reasoning. Please note that the post is written before Go generics. We used Go's code generation to solve high-performance needs with ease of use. Since we had so many big projects using err2 before Go 1.18 and generics, we offered a migration tool to port those repos to use the new Go generics-based err2 API if they wanted. Now the API relay on Go generics, and we drop the type variables.

I always nice to hear that others are working on the same problem area. I'm sure we can help each other!

-Harri
Reply all
Reply to author
Forward
0 new messages