func WithGlobalTx()

in pkg/tm/transaction_executor.go [43:84]


func WithGlobalTx(ctx context.Context, gc *GtxConfig, business CallbackWithCtx) (re error) {
	if gc == nil {
		return fmt.Errorf("global transaction config info is required.")
	}

	if gc.Name == "" {
		return fmt.Errorf("global transaction name is required.")
	}

	// open global transaction for the first time
	if !IsSeataContext(ctx) {
		ctx = InitSeataContext(ctx)
	}

	if IsGlobalTx(ctx) {
		clearTxConf(ctx)
	}

	if re = begin(ctx, gc); re != nil {
		return
	}

	defer func() {
		var err error
		deferErr := recover()
		// no need to do second phase if propagation is some type e.g. NotSupported.
		if IsGlobalTx(ctx) {
			// business maybe to throw panic, so need to recover it here.
			if err = commitOrRollback(ctx, deferErr == nil && re == nil); err != nil {
				log.Errorf("global transaction xid %s, name %s second phase error", GetXID(ctx), GetTxName(ctx), err)
			}
		}

		if re != nil || err != nil {
			re = fmt.Errorf("first phase error: %v, second phase error: %v", re, err)
		}
	}()

	re = business(ctx)

	return
}