Errors Handlings
Unlike almost all over the internet coaching you to use errors
package for creating error
object without reading through the specification available here: https://golang.org/pkg/errors/#New, I will use a different recipe for it. In this case, lesser package imports.
Standard Conventional Way
Now, the standard way recommended by many gopher is to use errors.New
function to create the error object. This is good if you're not doing any formatting to the error message and also a faster way to create one. The disadvantage however, is that you import an entirely new error package.
Here's an example shown in the specification, that needs both errors
package and fmt
package:
package main
import (
"errors"
"fmt"
)
func main() {
err := errors.New("emit macho dwarf: elf header corrupted")
if err != nil {
fmt.Print(err)
}
}
Notice that the author needs to import both fmt
package and error
package to fully manage the error
object? That's 2 packages in total.
Current Best Recipe
Now, if you see the second example, you will realize fmt
package actually allows you to create error
object without needing the error package: the fmt.Errof
function. This allows you to handle all error
object handling in one package. Here's the example from the specification:
package main
import (
"fmt"
)
func main() {
const name, id = "bimmler", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
if err != nil {
fmt.Print(err)
}
}
Therefore, I wouldn't need to import errors
package anymore just to manage error
objects.
That's all about errors
handling in Go. End of Lesson. Use the navigation bar to find the next recipe.