To prefer being terse over scattered error handling in Go. Used preferably in more than three or four consequent error checking.
The building block for using the whole library. This is a wrapper function to generalize handling result or error.
Same as Fn but accepts an input as argument.
Returns an error if either of errors passed to it is not nil. Otherwise the return value would be nil.
There are function calls that either return error or update a pointer passed to them the usual Go way to deal with them is:
iferr:=fooFunc(&fooStruct); err!=nil {
returnerr
}
iferr:=barFunc(&barStruct); err!=nil {
returnerr
}
iferr:=bazFun(&someOtherStructAgain); err!=nil {
returnerr
}
returnnilWe can summarize them as:
returnGetAny(fooFunc(&foorStruct), barFunc(&barStruct), bazFun(&someOtherStructAgain))Runs a series of functions; in case any of functions return an error, it will be returned, otherwise results is returned in an array.
There are function calls that either return error and nil for a value or return a value with a nil error:
ifv1, err:=fooFunc(fooVal); err!=nil {
returnerr
}
ifv2, err:=barFunc(barVal); err!=nil {
returnerr
}
ifv3, err:=bazFun(bazVal); err!=nil {
returnerr
}
returnnilWe can summarize (really?) them as:
vals, err: =GetValsOrError(
func () (interface{}, error) {
returnsayHi("John")
},
func () (interface{}, error) {
returnsayBy("John")
},
func () (interface{}, error) {
returnsayError("John")
}
)
println(err) // The error returned by sayError is printedvals, err: =GetValsOrError(
func () (interface{}, error) {
returnsayHi("John")
},
func () (interface{}, error) {
returnsayBy("John")
}
)
println(err) // nilprintln(vals[0].(string)) // Hi JohnSame as GetValsOrError, just runs the functions in go routines and waits till either all results are ready in the results array, or an error is returned from any functions.
Runs a series of functions passing the returning value of first one to the second and so on
When you want to run a series of functions passing the first output as second input and so on. If any errors occurs then that error is returned instead.
// We have these functions for demonstration------------funcAddOne(inpint) (int, error) {
returninp+1, nil
}
funcAddTwo(inpint) (int, error) {
returninp+2, nil
}
funcMulBy3(inpint) (int, error) {
returninp*3, nil
}
//------------------------------------------------------v1, err:=AddOne(1)
iferr!=nil {
returnnil
}
v2, err:=MulBy3(v1)
iferr!=nil {
returnnil
}
v3, err:=AddTwo(v2)
iferr!=nil {
returnnil
}
println(v3) // 8We can summarize them as:
ifv, err:=GetSeriesOrError(
1,
func(iinterface{}) (interface{}, error) {
returnAddOne(i.(int))
},
func(iinterface{}) (interface{}, error) {
returnMulBy3(i.(int))
},
func(iinterface{}) (interface{}, error) {
returnAddTwo(i.(int))
},
); err!=nil {
println(v) // 8
}The usefulness of package is more apparent when dealing with lots of errors to check.
For getting more familiar with the usage, take a look at the tests.