Home  >  Article  >  Backend Development  >  How to prevent unexpected crashes in golang

How to prevent unexpected crashes in golang

尚
Original
2020-03-27 14:44:223964browse

How to prevent unexpected crashes in golang

Whether it is a panic crash thrown by the runtime layer due to a code running error, or a panic crash actively triggered, defer and recover can be used to achieve error capture and recovery, so that the code can crash after it occurs. Then allow to continue running.

Go does not have an exception system. Its use of panic to trigger downtime is similar to throwing exceptions in other languages, so recover's downtime recovery mechanism corresponds to the try/catch mechanism.

Let the program continue executing when it crashes

The following code implements the ProtectRun() function, which passes in an anonymous function or an execution function after a closure, When the incoming function panics in any form, the error of the crash can be printed out, while allowing the subsequent code to continue running without causing the entire process to crash.

Protected running function:

package main
 
import (
"fmt"
"runtime"
)
 
// 崩溃时需要传递的上下文信息
type panicContext struct {
function string // 所在函数
}
 
// 保护方式允许一个函数
func ProtectRun(entry func()) {
 
// 延迟处理的函数
defer func() {
 
// 发生宕机时,获取panic传递的上下文并打印
err := recover()
 
switch err.(type) {
case runtime.Error: // 运行时错误
fmt.Println("runtime error:", err)
default: // 非运行时错误
fmt.Println("error:", err)
}
 
}()
 
entry()
 
}
 
func main() {
fmt.Println("运行前")
 
// 允许一段手动触发的错误
ProtectRun(func() {
 
fmt.Println("手动宕机前")
 
// 使用panic传递上下文
panic(&panicContext{
"手动触发panic",
})
 
fmt.Println("手动宕机后")
})
 
// 故意造成空指针访问错误
ProtectRun(func() {
 
fmt.Println("赋值宕机前")
 
var a *int
*a = 1
 
fmt.Println("赋值宕机后")
})
 
fmt.Println("运行后")
}

Explanation of the code:

Line 9 declares a structure that describes the error, and the members save the wrong execution function.

Line 17 uses defer to delay the execution of the closure. When panic triggers a crash, the ProtectRun() function will end running, and the closure after defer will be called.

On line 20, recover() obtains the parameters passed in by panic.

Line 22, use switch to perform type assertion on the err variable.

Line 23, if the error is a runtime error thrown by the Runtime layer, such as null pointer access, division by 0, etc., print the runtime error.

Line 25, other errors, print the passed error data.

In line 44, use panic to manually trigger an error and pass a structure with information. At this time, recover will obtain the structure information and print it out.

Line 57 simulates errors caused by null pointer assignment in the code. At this time, an error will be thrown by the runtime layer and captured by the recover() function of the ProtectRun() function.

The relationship between panic and recover

The combination of panic and defer has the following characteristics:

If there is panic but no recover, the program will crash.

With panic and recover capture, the program will not crash. After executing the corresponding defer, exit the current function from the crash point and continue execution.

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of How to prevent unexpected crashes 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