Skip to content

Instantly share code, notes, and snippets.

@danielstjules
Created January 20, 2015 00:12
Show Gist options
  • Save danielstjules/2c93a39b2748059394ac to your computer and use it in GitHub Desktop.
Save danielstjules/2c93a39b2748059394ac to your computer and use it in GitHub Desktop.
Error handling
type Foo struct {
Bar int
Baz string
Qux *exec.Cmd
}
func NewFoo() (*Foo, error) {
bar, err := getBar()
if err != nill {
return nil, err
}
baz, err := getBaz()
if err != nill {
return nil, err
}
qux, err := getQux()
if err != nill {
return nil, err
}
return &Foo{bar, baz, qux}, nil
}
// Imagine that the functions are defined below...
@danielstjules
Copy link
Author

I guess a similar example in JS using promises isn't really shorter:

function Foo(bar, baz, qux) {
  this.bar = bar;
  this.baz = baz;
  this.qux = qux;
}

// If the functions were all async and returned promises
function createFoo() {
  var bar, baz;

  return getBar().then(function(res) {
    bar = res;
    return getBaz();
  }).then(function(res) {
    baz = res;
    return getQux();
  }).then(function(qux) {
    return new Foo(bar, baz, qux);
  });
}

But if sync, standard try/catch is a bit more succinct:

function createFoo() {
  return new Foo(
    getBar(),
    getBaz(),
    getQux()
  );
}

try {
  createFoo();
} catch (e) {
  // handle error
}

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