In Go, when a program experiences panic (i.e., runtime error), the program will immediately stop the current execution process and return layer by layer on the function call stack until the recovery function or program terminates.
The function of the recover function is to capture this panic and restore the normal execution process. In the Gin framework, a recovery middleware is provided to automatically capture panic and convert it to HTTP 500 errors and return it to the client.
use
Using recover middleware is very simple, just add it in Gin route:
router := () (())
It should be noted that the recovery middleware should be declared in the first Gin route to ensure that all panics can be captured.
Cooperate with log printing and point reporting
In API development, when a user requests an interface, sometimes encounters some problems, such as access url errors, parameter errors, database connection timeouts, etc. Although the recovery middleware can avoid panic caused by program errors, it still needs to record these error information to assist in troubleshooting and positioning of problems.
Therefore, we can record these errors in conjunction with log printing and point reporting. Taking log printing as an example, the Gin framework provides the official Logger middleware, which can use Logger to record error information:
router := () // Logger middleware writes the requested URL, response time, response status code and requested IP address to the log file(()) // Recover middleware converts panic to 500 errors and writes it to log file(()) // Business code("/api", func(c \*) { // code if err != nil { // A function throws panic ("\[ERROR] - %v\n", err) (, { "message": "Internal error, please try again later", }) return } // code })
In the above code, we use log to log the error message and return an error message in the response. In this way, we can find problems in a timely manner and troubleshoot them.
Of course, we can also upload it to the point tool while recording error information, for exampleSentry、Zipkin
etc. to realize automatic error reporting and monitoring.
Use of recover in open source projects
Recover middleware is widely used in open source projects, such as Prometheus, etcd, Kubernetes and other projects.
Take etcd as an example, it uses the recover middleware to capture all panics and log error information in the log, as shown below:
func (s *EtcdServer) recoverAndLog(rctx , w , req *) { data, err := () if err != nil { writeError(w, rctx, err) return } defer func() { if v := recover(); v != nil { ("panic: %v", v) writeError(w, rctx, ("panic: %v", v)) } }() // code }
In this function, the recover function is called using the defer keyword to capture the panic, and the error message is recorded using the log and the error message is returned.
Summarize
Through the recovery middleware in the Gin framework, we can easily catch and handle program runtime errors, thereby improving the stability and reliability of API services. At the same time, cooperating with log printing and point reporting, error information and auxiliary problems can be better recorded. In open source projects, recover middleware is also widely used and has helped many projects to achieve stable operation.
This is the article about this detailed explanation of the recovery capture panic in Go advanced feature exploration. For more relevant Go recovery capture panic content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!