Error checking in Go: The try keyword.

This isn’t a complete proposal it only describes basic idea and the changes 
suggested.
The following are modifications that deals with some of the problems 
introduced in the original proposal 
<https://github.com/golang/proposal/blob/master/design/32437-try-builtin.md>
.

(I apologize if something very similar that uses a simple method to deal 
with adding context has been posted before but I could not find it.)

First, try is a keyword not a function builtin.

Here’s how error handling with the try keyword works:

try err

is equivalent to:

if err != nil {
    return err
} 

That’s it.

Example:

f, err := os.Open("file.dat")
try err
defer f.Close()

f.WriteString("...")

But, how to add context to errors?

 because try only returns if err != nil.
You can create a function that returns nil if an error is nil.

In fact, a function like this already exists in the errors package here.
https://github.com/pkg/errors/blob/master/errors.go

// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
    if err == nil {
        return nil
    }
    err = &withMessage{
        cause: err,
        msg:   message,
    }
    return &withStack{
        err,
        callers(),
    }
}

Example using it with try

f, err := os.Open("file.dat")
try errors.Wrap(err, "couldn't open file")
defer f.Close()

f.WriteString("...")

That’s it.

This should reduce repetitiveness with error handling in most cases.

It is very simple to understand, and it feels like Go.

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/dee8e2e6-9b05-4268-aa42-65eb143e2193%40googlegroups.com.

Reply via email to