Simplifying error handling in go -


in c , similar languages following shortcuts can applied detect error , stop on first non-zero result

(void)(result = dosomething() ||        result = dosomething() ||        result = dosomething() )  if (result == 0 && ... 

in golang, can't seem that.

for example:

if result = dosomething() || result = dosomething(); result < 0 { fmt.printf("error occurred\n"); }

c able treat integers boolean expression when checking non-zero.

for example can write

if (result = dosomething() || ... )  

instead of

if ( (result = dosomething()) == 0 || ... ) 

but in go, can't that.

i thought write:

if result = dosomething() == 0 ||    result = dosomething() == 0; result < 0 {    fmt.printf("error occurred\n"); } 

but error.

syntax error: result = dosomething() || result used value 

there has way of chaining these together. or in style of javascript promises dosomething().dosomething.dosomething.error() approach possible?

any creative solutions problem? i'm wanting avoid lots of repetitive code want whole bunch of things, if there error @ point stop. because error handling logic each same.

see errors values on the go blog. article, written rob pike, has interesting , powerful method of handling errors in group of functions works well.

i have used technique before several times, , works.

for reference, code used technique looks (copied article):

// helper type type errwriter struct {     w   io.writer     err error }  func (ew *errwriter) write(buf []byte) {     if ew.err != nil {         return     }     _, ew.err = ew.w.write(buf) }  //usage: ew := &errwriter{w: fd} ew.write(p0[a:b]) ew.write(p1[c:d]) ew.write(p2[e:f]) // , on if ew.err != nil {     return ew.err } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -