Error Printing in Go (Print Error)
While error messages might not be the most enticing or the most motivating thing to see in development, they do play a crucial role in helping to determine the next course of action and, more importantly, prevent the programs from premature termination.
In this tutorial, we will walk you through the process of printing the error messages in Go.
Before we get into the woods of learning how to create and use the custom errors in Go, let us understand the basics of error handling in Golang.
Go presents errors using the error interface. The error interface has a single method called Error() string. Any type that implements this method allows Go to treat it as error.
Here, take a look at the following example code:
In the given example, we use the errors.New() function which allows us to create a new error with a descriptive message when we attempt to divide by zero.
Working with Multiple Errors
In a complex situation, an app may encounter multiple errors that are tied. A common technique is aggregating the errors and return them as a single unit.
In Go, we can accomplish this using the fmt.Errorf() function as shown in the following example:
In this example, we are using the basic function operations to simulate the tasks that may return the errors. We then use the fmt.Errorf() function to combine them into single error messages.
Check our tutorial in Go error wrapping to learn more about how to add a context information to error messages.
In this tutorial, we learned how to work with error printing in Go using the new function and the “Errorf” function to combine multiple errors.