Skip to content

Instantly share code, notes, and snippets.

@bserdar
Created Oct 22, 2018
Embed
What would you like to do?
More explicit error handling

This is a suggestion to make error handling more explicit than what's described in the official proposal.

An error handler is declared as:

handle err { return err }

This declares err as an error variable, and an err_handler as a function of the form:

func err_handler(err error) error {
   return err // Include the function body from the handler definition
}

The err_handler is called (inlined) when err is assigned a non-nil value with a 'check' expression. So any code of the form:

  err:= check...

is translated to:

  err:=...
  if err!=nil {
     err_handler(err)
  }

Then error check/handling is done as follows:

  f, err=check os.Open(...)

Since err is an error and there is a handler for it, this translates to:

   f, err=os.Open(...)
   if err!=nil {
      err_handler(err) // inlined here
   }

This can also support := operator by redefining the err variable, but keeping the last defined err handler.

Multiple handlers can be defined:

handle error1 { return error1 }
handle error2 { return error2 }

x, error1:=check func1()
y, error2:=check func2()

Chanining errors is also possible, but more explicit:

handle error1 { return error1 }
handle error2 { error1=check fmt.Errorf("failed because %s", error2) }

x, error1:=check func1()
y, error2:=check func2()

This translates to:

   x, error1:=func1()
   if error1!=nil {
      return error1
   }
   y, error2:=func2()
   if error2!=nil {
       error1=fmt.Errorf("failed because %s",error2)
       if error1!=nil {
          return error1
       }
   }

An Alternative: no 'check'

In this proposal, handler will only be called if assignment is done via 'check' keyword. It should be also possible to omit 'check' completely and call the handler when error variable is assigned a non-nil value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment