How to check for and handle errors in Go using if err != nil?

In Go, you can check for and handle errors using the if err != nil pattern. Here's how you can do it:

  1. Make sure the function you are calling returns an error as one of its return values.

  2. Assign the returned value and the error to variables.

result, err := someFunction()
  1. Check if the error is nil using the if err != nil statement. If it is not nil, it means there was an error.
if err != nil { // Handle the error }
  1. Inside the if block, you can handle the error according to your application's needs. Some common error handling actions include logging the error, returning an error to the caller, retrying the operation, or performing alternative operations.

Here's an example of using the if err != nil pattern to handle an error:

package main import ( "fmt" "os" ) func main() { file, err := os.Open("nonexistent-file.txt") if err != nil { fmt.Println("Error:", err) return } defer file.Close() // Rest of the logic if the file was successfully opened }

In the example above, we attempt to open a file that doesn't exist. If an error occurs during the file opening process, it will be assigned to err. Inside the if block, we handle the error by printing it and returning from the main function.