Exception handling is a mechanism for handling unexpected errors in a program. The Go language provides panic and recover functions to handle exceptions. panic is used to output error information and terminate the program, and recover is used to recover from panic and continue execution. In practice, exception handling can be used in HTTP handlers to catch panics and send error responses when errors occur, preventing unexpected program termination and handling errors gracefully.
Exception handling in the Go function life cycle
Exception handling refers to unexpected or error conditions that occur in the handler. Go provides a structured way to handle exceptions through the built-in panic
and recover
functions.
Panic and Recover functions
When the program encounters a serious error that cannot be handled, you can use the panic
function to output the error message to standard error Output and terminate the program. recover
Function is used to recover from panic and continue program execution.
func main() { defer func() { if err := recover(); err != nil { log.Println(err) } }() // 可能抛出错误的代码 doSomething() } func doSomething() { // 产生错误 fmt.Println("错误") panic("自定义错误信息") }
In the above example, the doSomething
function may generate an error. We use the defer recover
statement to catch the panic and print its message to the log, then resume the execution of the program.
Practical case
The following is a practical case of using exception handling in HTTP handler:
func handleRequest(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { http.Error(w, "内部服务器错误", http.StatusInternalServerError) } }() // 处理请求的代码 data, err := getSomeData() if err != nil { panic(fmt.Sprintf("无法获取数据: %v", err)) } // 发送响应 w.Write(data) }
In this example, if## The #getSomeData function returns an error, which uses
panic to pass the error information to the
recover function.
recover The function captures the panic and sends the internal server error response to the client. This prevents the program from terminating unexpectedly and allows us to handle errors gracefully.
The above is the detailed content of Exception handling in Golang function life cycle. For more information, please follow other related articles on the PHP Chinese website!