Error Handling in Go Using the Errors Package

0


Error handling is one of the frequent operations in the software development cycle. It’s a crucial aspect of good programming. Go takes a simple and easy-to-use approach with its built-in mechanism for error handling. It’s based on returning errors from functions and methods, enabling you to focus on code functionality that is intuitive and easy to read.


You handle errors in Go explicitly, which results in a solid framework for feedback, with the ability to implement retry logic consistently. The errors package provides additional functionality for error handling.


The Errors Package

The errors package is one of the packages in Go’s standard library. The package provides simple error-handling primitives and functionalities for creating and manipulating errors consistently across Go code.

The package provides the New function for creating errors with custom error messages that you can use in the same fashion as any built-in error type, such as the nil and Error method of the error interface.

The errors package also provides functionality for wrapping and unwrapping errors, a method for type assertions on errors.

You can import the errors package with the import keyword. Simply specify the name of the package in your list of imports.

 import "errors"

Catching and Handling Errors in Go

Knowledge of basic error handling in Go lays the foundation for understanding the errors package. Functions and methods return errors that are accompanied by a resource.

Here’s an example of error handling from a file opening operation with the built-in os package.

 package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("filename.txt")

    if err != nil {
        fmt.Println(err)
    }

    
}

The Open method of the os package is useful when working with text files in Go. It opens a file, returning an open file instance and an error.

The error value could be the nil type, indicating no errors. However, you can check for a non-nil case and handle an error if it’s present. In the case above, the if block prints the error.

You can access the Error method of an error to extract more information about the error (usually a description).

 if err != nil {
    fmt.Println(err.Error())
}

For example, if the file does not exist, you’ll see an error message that looks something like this:

error from the file opening operation

Creating Errors in Go

You can create errors with the New method of the errors package. This method takes in a string message and returns encountered errors.

 import "errors"

func main() {
    err := errors.New("something went wrong")

    if err != nil {
        
    }
}

The main function creates a new error and handles possible errors from the error creation with an if statement.

You can also define custom errors in Go. The conventional method uses a struct and an error function to implement the struct based on the error’s functionality.

 package main

import "fmt"

type customError struct {
    info string
}

func main() {
    
    err := customError{
        info: "Something went wrong!",
    }

    
    fmt.Println(err)
}

The customError struct is the blueprint for the error, and the info string field will hold the error message.

Your error functions can implement the customError struct and return an error string.

 func (ce customError) Error() string {
    return fmt.Sprintf("A custom error occurred: %v", ce.info)
}

The Error method of the customError struct returns a string using the Sprintf formatting method of the fmt package.

Wrapping and Unwrapping Errors in Go

You can add further contextual information to errors by wrapping them. You’ll primarily use wrapped errors to create clear error messages for precision in debugging.

You can use the Errorf method of the fmt package that provides functionality for formatting error messages to wrap errors. The Errorf method takes in a string and string formatting verb and the error and returns the wrapped error.

 import (
    "fmt"
    "os"
)

func main() {
    _, err := os.Open("filename.txt")

    if err != nil {
        wrappedErr := fmt.Errorf("Error opening file: %v", err)
        fmt.Println(wrappedErr)
    }
}

The main function opens a file with the os package’s Open method and wraps the error with the Errorf method of the fmt package. It then outputs the wrapped error to the console.

You can unwrap wrapped errors in your programs with the Unwrap method of the errors package. The Unwrap method takes in the wrapped error and returns the unwrapped error.

 import (
    "fmt"
    "os"
    "errors"
)

func main() {
    _, err := os.Open("filename.txt")

    if err != nil {
        wrappedErr := fmt.Errorf("Error opening file: %v", err)
        unwrappedErr := errors.Unwrap(wrappedErr)
        fmt.Println(unwrappedErr)
    }
}

The main function wraps an error from a file opening operation, and the unwrappedErr variable holds the unwrapped error.

Log Your Error Reports With These Third-Party Logging Packages

You’ll need to log some errors for later reviews, debugging, and other operations during your application development process. You can use the zap package by Uber, Logrus, Zerolog, and Log15 packages for fast, structured logging.

Source
Las Vegas News Magazine

Leave A Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More