search
HomeBackend DevelopmentGolangHow to handle errors in golang

How to handle errors in golang

Dec 23, 2022 am 11:08 AM
golanggo languageError handling

Golang usually has three error handling methods: error sentinel (Sentinel Error), error type assertion and recording error call stack. The error sentinel refers to using a variable with a specific value as the judgment condition for the error processing branch. Error types are used to route error handling logic and have the same effect as error sentries. The type system provides uniqueness of error types. The error black box refers to not caring too much about the error type and returning the error to the upper layer; when action needs to be taken, assertions must be made about the error behavior rather than the error type.

How to handle errors in golang

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Golang does not provide try-catch similar error handling mechanism. It adopts C language style error handling at the design level and returns error information through function return values. The specific examples are as follows :

func ReturnError() (string, error) {
	return "", fmt.Errorf("Test Error")
}

func main() {
	val, err := ReturnError()
	if err != nil {
		panic(err)
	}
	fmt.Println(val)
}

The above example is a basic error handling example. The call stack executed in a production environment is often very complex, and the returned error is also varied. It is often necessary to return The error message determines the specific error handling logic.

Golang usually has the following three error handling methods, error sentinel (Sentinel Error), error type assertion (Error Type Asseration) and recording error call stack.

Error Sentinel (Sentinel Error)

Sentinel refers to using a variable with a specific value as the judgment condition of the error processing branch. Common application scenarios include # in gorm. ##gorm.RecordNotFounded and redis.NIL in the redis library.

Golang can compare variables of the same type, and interface variables compare the addresses of pointers pointed to by the interface. Therefore, if and only if the

error type variable points to the same address, the two variables are equal, otherwise they are not equal.

var ErrTest = errors.New("Test Error")

err := doSomething()
if err == ErrTest{
	// TODO: Do With Error
}

There are the following problems when using Sentinel. There are two problems:

1. The code structure is not flexible, and branch processing can only use

== or ! = Make a judgment. If things go on like this, it is easy to write spaghetti-like code.

var ErrTest1 = errors.New("ErrTest1")
var ErrTest2 = errors.New("ErrTest1")
var ErrTest3 = errors.New("ErrTest1")
……
var ErrTestN = errors.New("ErrTestN")
……
if err  == ErrTest1{
	……
} else if err == ErrTest2{
	……
}else if err == ErrTest3{
	……
}
……
else err == ErrTestN{
	……
}

2. The value of the sentinel variable cannot be modified, otherwise it will cause a logic error. The error sentinel in the above golang writing method can be changed, which can be solved in the following ways:

type Error string

func (e Error) Error() string { return string(e) }

3. The sentinel variable will This leads to extremely strong coupling, and the spitting out of new errors in the interface will cause users to modify the code accordingly and create new processing errors.

Compared with the above solution, Error Sentinel has a more elegant solution that relies on interfaces instead of variables:

var ErrTest1 = errors.New("ErrTest1")

func IsErrTest1(err error) bool{
  return err == ErrTest1
}

Error type

Error types are used to route error processing logic, which has the same effect as error sentries. The type system provides the uniqueness of error types. The usage method is as follows:

type TestError {
}
func(err *TestError) Error() string{
	return "Test Error"
}
if err, ok := err.(TestError); ok {
	//TODO 错误分支处理
}

err := something()
switch err := err.(type) {
case nil:
        // call succeeded, nothing to do
case *TestError:
        fmt.Println("error occurred on line:", err.Line)
default:
// unknown error
}

Compared with sentinels, the immutability of error types changes Good, and

switch can be used to provide elegant routing strategies. But this makes it impossible for users to avoid excessive dependence on packages.

Using the interface to throw more complex and diverse errors still requires changing the caller's code.

Error black box (depends on error interface)

Error black box refers to not paying too much attention to the error type and returning the error to the upper layer. When action is required, make assertions about the behavior of the error, not the type of error.

func fn() error{
	x, err := Foo()
	if err != nil {
		return err
	}
}

func main(){
	err := fn()
	if IsTemporary(err){
		fmt.Println("Temporary Error")
	}
}

type temporary interface {
        Temporary() bool
}
 
// IsTemporary returns true if err is temporary.
func IsTemporary(err error) bool {
        te, ok := err.(temporary)
        return ok && te.Temporary()
}

In this way, 1. Dependencies between interfaces are directly decoupled, 2. Error handling routing has nothing to do with error types, but is related to specific behaviors, avoiding the expansion of error types.

Summary

Error sentinels and error types cannot avoid the problem of excessive dependence. Only the error black box can change the problem from the processing logic of determining the error type (variable) to To determine wrongdoing. Therefore it is recommended to use the third way to handle errors.

It is necessary to add one sentence here,

Black box processing, returning an error does not mean ignoring the existence of the error or directly ignoring it, but it needs to be handled gracefully in the appropriate place. In this process, you can use errorsWrap, Zaplogging, etc. to record the context information of the calling link as errors are returned layer by layer. .

func authenticate() error{
	return fmt.Errorf("authenticate")
}

func AuthenticateRequest() error {
	err := authenticate()
	// OR logger.Info("authenticate fail %v", err)
	if err != nil {
		return errors.Wrap(err, "AuthenticateRequest")
	}
	return nil
}

func main(){
	err := AuthenticateRequest()
	fmt.Printf("%+v\n", err)
	fmt.Println("##########")
	fmt.Printf("%v\n", errors.Cause(err))
}

// 打印信息
authenticate
AuthenticateRequest
main.AuthenticateRequest
	/Users/hekangle/MyPersonProject/go-pattern/main.go:17
main.main
	/Users/hekangle/MyPersonProject/go-pattern/main.go:23
runtime.main
	/usr/local/Cellar/go@1.13/1.13.12/libexec/src/runtime/proc.go:203
runtime.goexit
	/usr/local/Cellar/go@1.13/1.13.12/libexec/src/runtime/asm_amd64.s:1357
##########
authenticate

【Related recommendations:

Go video tutorial, Programming teaching

The above is the detailed content of How to handle errors in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.