当前位置: > > > > Go 中 for 循环内的错误处理可能会导致下一次迭代
来源:stackoverflow
2024-04-24 22:33:33
0浏览
收藏
哈喽!今天心血来潮给大家带来了《Go 中 for 循环内的错误处理可能会导致下一次迭代》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
我很难使用特定的 go 实现来将日志文件发送到不同的位置:
package main func isDestinationSIEM(json_msg string, json_obj *jason.Object, siem_keys []string) (bool) { if json_obj != nil { dest, err := json_obj.GetString("destination") if err == nil { if strings.Contains(dest,"SIEM") { return true } } for _, key := range siem_keys { if strings.Contains(json_msg, key) { return true } } } return false } func sendToSIEM(siem_dst string, json_msg string) (error) { // Create connection to syslog server roots := x509.NewCertPool() ok := roots.AppendCertsFromPEM([]byte(rootPEM)) if !ok { fmt.Println("failed to parse root certificate") } config := &tls.Config{RootCAs: roots, InsecureSkipVerify: true} conn, err := tls.Dial("tcp", siem_dst, config) if err != nil { fmt.Println("Error connecting SIEM") fmt.Println(err.Error()) } else { // Send log message _, err = fmt.Fprintf(conn, json_msg) if err != nil { fmt.Println("Error sending SIEM message: ", json_msg) fmt.Println(err.Error()) } } defer conn.Close() return err } func main() { // simplified code otherwise there would have been too much // but the 'devil' is this for loop for _, obj := range objects { // first check isSIEM := isDestinationSIEM(obj, siem_keys) if isSIEM { err := sendToSIEM(obj) if err != nil { // print error } isAUDIT:= isDestinationSIEM(obj) if isAUDIT { err := sendToAUDIT(obj) if err != nil { // print error } } // end of for }
当“if issiem”返回错误时,不会进行第二次检查“if isaudit”。 为什么是这样?如果返回错误,循环是否从下一次迭代开始?
错误看起来像这样: 运行时错误:无效的内存地址或零指针取消引用:errorstring(列出了几个 go 包)
解决方案
错误看起来像这样:运行时错误:无效的内存地址或零指针取消引用:errorString(列出了几个 go 包)
这意味着您捕获了 panic()
并且您的程序已停止,这意味着您的圈子 for
也已停止。
这里详细介绍了如何处理恐慌
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注公众号,一起学习编程~