Handling Errors

Powerful Command-Line Applications in Go — by Ricardo Gerardi (61 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Executing External Programs | TOC | Writing Tests for Goci 👉

At this point your application handles errors by defining error strings, using the function fmt.Errorf from package fmt. This is a valid approach for small applications, but it’s harder to maintain as your application grows in complexity. For instance, relying only on comparing the error message isn’t a resilient method as the error message may change.

As an alternative, in Developing the Initial Version of colStats, you handled errors by defining error values as exported variables. You can use this approach here to handle simple errors, such as validating input parameters. Add a file errors.go to your project and edit it. Add the package definition and the import section. For this file, you’re using the package errors to define error values, and the package fmt to format messages:

processes/goci.v1/errors.go

​ ​package​ main

​ ​import​ (
​ ​"errors"​
​ ​"fmt"​
​ )

Now add the error value variable ErrValidation representing a validation error:

processes/goci.v1/errors.go

​ ​var​ (
​ ErrValidation = errors.New(​"Validation failed"​)
​ )

Save and close this file and edit the file main.go. Update the line that returns the project directory validation error. Use the verb %w from fmt.Errorf…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.