如何知道延迟函数是在成功执行函数后调用还是被 panic 调用

How to know a defer function is called after successfully executing the function or by a panic

我需要在 defer 函数中写一些业务逻辑。 defer中的控制流应该根据defer是在系统panic后执行还是在函数执行成功后执行。

package main

import "log"

func b() {
    panic("panicked in b")
}
func a() {

    b()
}
func main() {
    defer func() {
     // If panicked 
         log.Println("panicked")
         // if called after function successfully executed
         log.Println("Success")
         /* 
            How to understand if defer is triggered by panic or after function returned successfully.
         */
    }()
    a()
    log.Println("main code")
}

预期:Defer 应该能够通过任何可能的方式知道它被 panic 调用

您可以使用 recover 来捕捉恐慌:

defer func() {
    if err := recover(); err != nil {
        fmt.Println("panic")
    } else {
        fmt.Println("successful")
    }
}()