Testing for Errors on Functions
Explore how to properly test and handle errors in Go functions. Understand the comma, ok pattern, learn to check error returns, and manage error conditions to write more reliable Go programs. This lesson helps you implement effective error handling and control flow in your code.
We'll cover the following...
Testing support
Sometimes, functions in Go are defined so that they return two results. One is the value and the other is the status of the execution. For example, the function will return a value and true in case of successful execution. Whereas, it will return a value (probably nil) and false in case of an unsuccessful execution.
Instead of true and false, an error-variable can be returned. In the case of successful execution, the error is nil. Otherwise, it contains the error information. It is then obvious to test the execution with an if statement because of its notation; this is often called the comma, ok pattern.
Consider the following example:
v, ok = sample_function(parameter)
Here, the comma, ok pattern is being ...