SoFunction
Updated on 2025-03-05

In-depth analysis of error handling in Golang

1. Go's built-in type error

The error type is actually an interface type, and it is also a built-in type of the GO language;

Only one method Error is included in the declaration of this interface type;

The Error method does not accept any arguments, but returns a result of type string.

Can be passed(string) errorMethod declares a variable of type error;

Generate error messages in a modular way, you can use

This method is equivalent to calling it firstGet the exact error message and call itFunction, get the error type value containing error information. Finally, the value is returned.

Case using error:

package main
import (
	"errors"
	"fmt"
)
func echo(request string) (response string, err error) {
	if request == "" {
		err = ("empty request")
		return
	}
	response = ("echo: %s", request)
	return
}
func main() {
	for _, request := range []string{"", "hello!"} {
		("request: %s\n", request)
		resp, err := echo(request)
		if err != nil {
			("error: %s\n", err)
			continue
		}
		("response: %s \n", resp)
	}
}

2. How to determine which type of error value represents

  • For a series of errors in a known range of types, a type assertion expression or a type switch statement is generally used to judge;
  • For a series of errors that already have corresponding variables and have the same type, we generally use judgment operations directly to judge;
  • For a series of error values ​​that do not have corresponding variables and have unknown types, they can only be judged using the string representation of their error information;

Know the scope of the error type

import (
	"os"
	"os/exec"
)
func underlyingError(err error) error {
	switch errtype := err.(type) {
	case *:
		return 
	case *:
		return 
	case *:
		return 
	case *:
		return 
	default:
		return err
	}
}

Know what values ​​are the error variables

func knownError(err error) {
	switch err {
	case :
		("errClosed")
	case :
		("errInvalid")
	case :
		("errPermission")
	}
}

3. Two methods of error value system

Three-dimensional - error type system

Use types to establish a tree-shaped error system, and use unified fields to establish a chain error relationship that can trace the root.

  • Use error as an embedded interface.
  • Use a field named Err and type error interface type to represent the potential error of the current error. Another relationship between values ​​of error types: chain relationship.

Flat - Error Value List

passThe function generates error values, creating some error values ​​that represent known errors in advance.

Hidden danger: ByThe error value generated by the function can only be assigned to variables, but not to constants. Also, because these variables need to be used for out-of-package code, they can only be public. The problem brought about by this: the malicious code changes the value of the variable, and the results of corresponding judgments and other operations will also change.

Solution 1: Privatize variables, that is, let the initial letter be lowercase, and then write a public function for obtaining error values ​​and determining error values ​​such as those.

Solution 2: This solution exists in the syscall package, using one of the types called Errno, which represents the underlying error that may occur during system calls. This error type is the implementation type of the error interface, and it is also a redefinition type of the built-in type uintptr. Since uintptr can be used as a constant type,It can also be used as an incorrect constant type. We can build our own list of error values ​​in this way.

This is the end of this article about in-depth analysis of error handling in Golang. For more related Go error handling content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!