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.

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.
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.
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!
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:
C and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AMC is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
Golang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AMGolang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.
Golang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AMThe core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.
Golang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PMGo language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.
Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PMConfused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







