Hi, guys, I want to know which error handling pattern do you prefer. Following is a code snippet from go stdlib.
Let me simplify my questions:
Pattern1: like the code in go stdlib, in the same function, we first declare one error variable, then in the following if-statement we use one-liner pattern to declare a new error variable.
```go
func MyFunc() error {
v, err := doSomething()
if err != nil {
return err
}
// stuff about processing `v`
if err := doAnotherthing(); err != nil {
return err
}
// stuff about processing ...
}
```
I think pretty code should not only be readable but also to conform to same code style. So I think why not use the already declared variable before. Then we have the following pattern.
Pattern2: Firstly doSomething() returns multiple return values and we need processing `v` later, so we use `v, err := doSomething()` as before. But, I think the `error` encountered is special compared to other local variables, it represents a state of current function (success or failure). So I think only one error variable is enough, it can be used for indicating any error, no matter the error is generated from `doSomething()` or `doAnotherthing()`.
And, I didn't use the one-liner pattern which may be used for minimize the variable's scope. Some people think we should use one-line pattern here to conform to this rule.
```go
func MyFunc() error {
v, err := doSomething()
if err != nil {
return err
}
// stuff about processing `v`
err := doAnotherthing()
if err != nil {
return err
}
// stuff about processing ...
}
```
Of course I know the rule to minimize the variable's scope, but I think error is special and consistent coding style is important and beautiful. I searched the go source code, these two patterns are both used.
I want to know which pattern do you prefer and suggested.
Thanks!