In go errors are values, and hence error management is an explicit process. There is no exception handling or bubbling them up, you get an error and you decide what do with it often leading to verbose scenarios as below
value, err := someFunc()
if err != nil {
log.Fatal(err)
}
While writing a tool recently, one of my use cases had a method invoking some system functions. This led me to a scenario to return back formatted error messages, and to do that I ended up with fmt.Errorf()
[1]
It allows us to return formatted errors like below
result, err := externalFunc()
if err != nil {
return fmt.Errorf("Calling external function failed: %s", err)
}
errors.New()
doesn't allow us to format text, but only pass a string. Otherwise we would have to use Sprintf
or equivalent to create a formatted string and then pass to errors.New()
. Although, guess what, that's what the method internally does.
References:
[1] https://godoc.org/fmt#Errorf
Top comments (0)