Skip to content

Instantly share code, notes, and snippets.

@ki-ichino
Created July 25, 2019 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ki-ichino/bac8268a237bc16ab8b5eca44b243ce8 to your computer and use it in GitHub Desktop.
Save ki-ichino/bac8268a237bc16ab8b5eca44b243ce8 to your computer and use it in GitHub Desktop.

go2-error-handling-proposal

I propose try-return statements.

Syntax

"try" IdentifierList ( ":=" | "=" ) ExpressionList "return" ExpressionList

e.g. try a, err := foo() return err

  1. Perform variable declarations or assignments.
  2. If the value of the rightmost variable is zero-valued, evaluate the second ExpressionList and return.

Examples

Transparent Error

// Conventional
a, b, err := foo()
if err != nil {
    return err
}

// Proposed
try a, b, err := foo() return err

New (or Wrapped) Error

try a, b, err := foo() return errors.New("A new error")

Custom Error Handler

myErrorHandler := func(err error) error {
    doSomething()
    return err
}

try a, b, err := foo() return myErrorHandler(err)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment