Go language defer and recover

Keywords: Web Server Go

1.defer is the code segment executed when the function returns. Whether it is return or panic, the code snippet in defer will be executed.

2.recover is used to capture panic in the defer code segment. When panic occurs, the defer code segment will be executed, in which if recover is available,

The panic will be captured and used for user-defined processing. You can choose how to handle the panic, ignore it and let the process not stop running, or

Let him panic. In turn, it can be derived to process some of the panics we want, while other panics stop the process.

Upper Code:

type TestS struct {
	tp *TestP
}

type TestP struct {
	id_ int
}

func SetTestS(){
	fmt.Println("begin SetTestS")
	ts := &TestS{}
	ts.tp = &TestP{}
	ts.tp.id_ = 1
	fmt.Println("end SetTestS")
}

func SetTestSErr(){
	defer func() {
		fmt.Println("defer SetTestSErr")
	}()
	fmt.Println("begin SetTestSErr")
	ts := &TestS{}
	ts.tp.id_ = 1    //Null pointer exception
	fmt.Println("end SetTestSErr")
}

func SetTestSWithRecover(){
	fmt.Println("begin SetTestSWithRecover")
	defer func() {
		if p := recover(); p != nil{
			fmt.Println("panic SetTestSWithRecover")
		}
	}()
	ts := &TestS{}
	ts.tp.id_ = 1    //Null pointer exception
	fmt.Println("end SetTestSWithRecover")
}

func main()  {
	//SetTestS()
	//SetTestSErr()
	//SetTestSWithRecover()
}

The output of the three functions is

SetTestS(): 
begin SetTestS
end SetTestS
SetTestSErr(): 
begin SetTestSErr
defer SetTestSErr
panic: runtime error: invalid memory address or nil pointer dereference
SetTestSWithRecover(): 
begin SetTestSWithRecover
panic SetTestSWithRecover
SetTestSErr and settestswitchrecover functions

The implementation results of 1 and 2 were verified respectively.

If we want to deal with special panic, we can write as follows:

func SetTestS(){
	fmt.Println("begin SetTestS")

	type EightyPanic struct {}
	defer func() {
		switch p := recover(); p {
		case EightyPanic{}:
			fmt.Println("EightyPanic")
		default:
			panic(p)
		}
	}()
	panic(EightyPanic{})    //Throw custom panic
	fmt.Println("end SetTestS")
}
In the book, there is the cloud go language Bible:

net/http package provides a web server to distribute the received requests to the processing functions provided by users. Obviously, we can't kill the whole process because of the panic exception caused by a processing function; when the web server encounters the panic caused by the processing function, it will call recover, output the stack information, and continue to run. Such an approach is very convenient in practice, but it can also cause resource leakage or other problems due to the recover operation.



Posted by Dongowarrior on Thu, 13 Feb 2020 12:45:04 -0800