Detailed explanation of the errors package in Golang

In Golang, the errors package is a standard library for handling errors. The functions provided by the errors package are relatively simple and very convenient to use. Next, let's explain in detail several functions provided by the errors package.

errors.New

func New(text string) error

Error handling is essential in the development process, use the errors.New function to create an object that represents a specific error. Accepts a parameter of type string (used to describe the error message), and returns a value of type error. For example:

package main

import "errors"

func main() {
	err := errors.New("invalid input")
}

The error type is an interface defined in the builtin package, defined as follows:

type error interface {
	Error() string
}

It can be seen that this interface defines a basic Error method for returning error description information.

package main

import (
	"errors"
	"fmt"
)

func main() {
	err := errors.New("invalid input")
	errDesc := err.Error()
	fmt.Println(errDesc) // 输出 invalid input
}

errors.Is

func Is(err, target error) bool

Used to determine whether a given error is the target error type or an error wrapped based on the target error type. The error chain will be checked recursively until the target error type is found or the end of the error chain is reached. Returns true if the target error type is found, false otherwise. Look at an example:

package main

import (
	"errors"
	"fmt"
)

func main() {
	err := errors.New("invalid input")
	err1 := errors.New("invalid input")
	err2 := fmt.Errorf("err2: [%w]", err)
	fmt.Println(errors.Is(err1, err)) // false
	fmt.Println(errors.Is(err2, err)) // true
}

Because both err and err1 are created using the errors.New function, using Is to judge will return false. err2 is packaged based on err, so using Is to judge will return true.

errors.AS

func As(err error, target any) bool

Used to convert an error into a specific type of error, the As function will check whether err is an instance of the type pointed to by target, and if so, assign the instance to target and return true. Otherwise return false. Look at an example:

package main

import (
	"errors"
	"fmt"
)

type MyError struct {
	Message string
}

func (e *MyError) Error() string {
	return e.Message
}
func main() {
	err := &MyError{
		Message: "This is a custom error",
	}
	var target *MyError
	if errors.As(err, &target) {
		fmt.Println("Custom error found:", target.Message)
	} else {
		fmt.Println("Custom error not found")
	}
}

Use errors.As to check whether err is an instance of type MyError and assign the instance to target. Run the example to see the effect

$ go run main.go
Custom error found: This is a custom error

This function is usually used to handle different types of errors, and take corresponding processing methods according to the type of error.

errors.Unwrap

func Unwrap(err error) error

It is used to expand an error object to get the next layer of error objects. If the error object has no next layer of error objects, it returns nil. Look at an example:

package main

import (
	"errors"
	"fmt"
)

func main() {
  originalErr := errors.New("original error")
	err := fmt.Errorf("error: %w", originalErr)
	unwrappedErr := errors.Unwrap(err)
	fmt.Println(unwrappedErr) // 输出: original error
}

Use the fmt.Errorf function to wrap originalErr to get err, and then use Unwrap to unwrap err and get the error object originalErr before wrapping. Note that Unwrap can only unwrap error objects wrapped by fmt.Errorf. If you want to expand other types of error objects, you can use the type assertion operator `.` for type assertion.

summary

The errors package provides some simple and easy-to-use functions to process and obtain error information. With the help of the errors package, a very powerful error handling function can be realized.

Guess you like

Origin blog.csdn.net/luduoyuan/article/details/131565907