Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go — handling multiple errors elegantly?

Tags:

go

Is there a way to clean up this (IMO) horrific-looking code?

    aJson, err1 := json.Marshal(a)
bJson, err2 := json.Marshal(b)
cJson, err3 := json.Marshal(c)
dJson, err4 := json.Marshal(d)
eJson, err5 := json.Marshal(e)
fJson, err6 := json.Marshal(f)
gJson, err4 := json.Marshal(g)
if err1 != nil {
    return err1
} else if err2 != nil {
    return err2
} else if err3 != nil {
    return err3
} else if err4 != nil {
    return err4
} else if err5 != nil {
    return err5
} else if err5 != nil {
    return err5
} else if err6 != nil {
    return err6
} 

Specifically, I'm talking about the error handling. It would be nice to be able to handle all the errors in one go.

like image 510
Matthew H Avatar asked Mar 13 '13 22:03

Matthew H


People also ask

Which of the following is considered good practices when handling errors in Golang?

Golang just provides you how to return and use the errors; further, Error handling in golang handling the Go errors is entirely up to you. Golang prefers to use the panic and recover method rather than throwing exceptions and using try… catch block.

How does Go handle errors?

Go's built-in errors don't contain stack traces, nor do they support conventional try / catch methods to handle them. Instead, errors in Go are just values returned by functions, and they can be treated in much the same way as any other datatype - leading to a surprisingly lightweight and simple design.

What is a sentinel error?

Sentinel errors are usually used to indicate that you cannot start or proceed.

Does Go exceptions Go handle errors?

Go solves the exception problem by not having exceptions. Instead Go allows functions to return an error type in addition to a result via its support for multiple return values. By declaring a return value of the interface type error you indicate to the caller that this method could go wrong.


2 Answers

var err error
f := func(dest *D, src S) bool {
    *dest, err = json.Marshal(src)
    return err == nil
} // EDIT: removed ()

f(&aJson, a) &&
    f(&bJson, b) &&
    f(&cJson, c) &&
    f(&dJson, d) &&
    f(&eJson, e) &&
    f(&fJson, f) &&
    f(&gJson, g)
return err
like image 137
zzzz Avatar answered Sep 28 '22 05:09

zzzz


You can create a reusable method, then catch error only one if condition. This implementation will only show last error though.

func hasError(errs ...error) error {
    for i, _ := range errs {
        if errs[i] != nil {
            return errs[i]
        }
    }
    return nil
}

aJson, err := json.Marshal(a)
bJson, err2 := json.Marshal(b)
cJson, err3 := json.Marshal(c)
dJson, err4 := json.Marshal(d)
eJson, err5 := json.Marshal(e)
fJson, err6 := json.Marshal(f)
gJson, err7 := json.Marshal(g)

if error := util.hasError(err, err1, err2, err3, err4, err5, err6, err7); error != nil {
    return error
}
like image 36
Lucas Avatar answered Sep 28 '22 05:09

Lucas