gopanicdefer-keyword

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


I need to write some business logic in defer function. Control flow in defer should be based on whether the defer is executed after the system panicked or after the successful execution of the function.

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")
}

Expected: Defer should be able to know its called by panic by any possible way


Solution

  • You can use recover to catch the panic:

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