github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zerror/catch.go (about)

     1  package zerror
     2  
     3  import (
     4  	"fmt"
     5  )
     6  
     7  // TryCatch exception capture
     8  func TryCatch(fn func() error) (err error) {
     9  	defer func() {
    10  		if recoverErr := recover(); recoverErr != nil {
    11  			switch e := recoverErr.(type) {
    12  			case error:
    13  				err = Reuse(e)
    14  			case *Error:
    15  				err = e
    16  			default:
    17  				err = Reuse(fmt.Errorf("%v", recoverErr))
    18  			}
    19  		}
    20  	}()
    21  	err = fn()
    22  	return
    23  }
    24  
    25  // Panic if error is not nil, usually used in conjunction with TryCatch
    26  func Panic(err error) {
    27  	if err != nil {
    28  		panic(Reuse(err))
    29  	}
    30  }