github.com/sandwich-go/boost@v1.3.29/xpanic/cach.go (about)

     1  package xpanic
     2  
     3  // Panic is a snapshot of a panic, containing both the panic's reason and the
     4  // system stack.
     5  type Panic struct {
     6  	// Reason is the value supplied to the recover function.
     7  	Reason interface{}
     8  }
     9  
    10  // Catch recovers from panic. It should be used as a deferred call.
    11  //
    12  // If the supplied panic callback is nil, the panic will be silently discarded.
    13  // Otherwise, the callback will be invoked with the panic's information.
    14  func Catch(cb func(p *Panic)) {
    15  	if reason := recover(); reason != nil && cb != nil {
    16  		cb(&Panic{
    17  			Reason: reason,
    18  		})
    19  	}
    20  }
    21  
    22  // Do executes f. If a panic occurs during execution, the supplied callback will
    23  // be called with the panic's information.
    24  //
    25  // If the panic callback is nil, the panic will be caught and discarded silently.
    26  func Do(f func(), cb func(p *Panic)) {
    27  	defer Catch(cb)
    28  	f()
    29  }