package entx import ( "context" "fmt" "git.noahlan.cn/noahlan/ntool/nlog" "{{.package}}/ent" ) // WithTx uses transaction in ent. func WithTx(ctx context.Context, client *ent.Client, fn func(tx *ent.Tx) error) error { tx, err := client.Tx(ctx) if err != nil { nlog.Errorw("failed to start transaction", nlog.Field("err", err.Error())) return err } defer func() { if v := recover(); v != nil { tx.Rollback() panic(v) } }() if err := fn(tx); err != nil { if rollBackErr := tx.Rollback(); rollBackErr != nil { err = fmt.Errorf("%w: rolling back transaction: %v", err, rollBackErr) } nlog.Errorw("errors occur in transaction", nlog.Field("err", err.Error())) return err } if err := tx.Commit(); err != nil { nlog.Errorw("failed to commit transaction", nlog.Field("err", err.Error())) return err } return nil }