Читать книгу Practical Go - Amit Saha - Страница 42
Removing Duplicate Error Messages
ОглавлениеYou may have noticed that errors were being displayed twice. This is caused by the following code snippet in the main()
function:
c, err := parseArgs(os.Stderr, os.Args[1:]) if err != nil { . fmt.Println(err) os.Exit(1) }
When the Parse()
function call encountered an error, it was displaying that error to the output writer instance set in the fs.SetOutput()
call. Subsequently, the returned error was also being printed in the main()
function via the snippet above. It may seem like an easy fix not to print the error in the main()
function. However, that will mean that any custom errors returned, such as when positional arguments are specified, will also not be shown. Hence, what we will do is create a custom error value and return that instead. We will only print the error if it matches that custom error, else we will skip printing it.
A custom error value can be created as follows:
var errPosArgSpecified = errors.New("Positional arguments specified")
Then, in the parseArgs()
function, we return the following error:
if fs.NArg() != 0 { . return c, errPosArgSpecified }
Then in main()
, we update the code as follows:
c, err := parseArgs(os.Stderr, os.Args[1:]) if err != nil { if errors.Is(err, errPosArgSpecified) { fmt.Fprintln(os.Stdout, err) } os.Exit(1) }
The errors.Is()
function is used to check whether the error value err
matches the error value errPosArgSpecified
. The error is displayed only if a match is found.