The first son did evil in the sight of God and was killed. We are not given the reason. Under the Levirate law at the time, Onan was asked to marry his bother’s widow, Tamar, in order to procreate offspring in his brother’s name. Onan married her but when he had intercourse, he went through the motions, then spilled his seed on the ground. In medical terminology, this is called “coitus interruptus”.
More commonly, it is called “withdrawal” and is a form of contraception. Onan did this because he did not want to have children under his dead brother’s name. God killed him. It is clear that God killed him because he defrauded the marriage of its procreative purpose.Tamar later went on to have illicit sex with Judah, her father-in-law. Tamar bore twins. Despite their sins, neither she, Judah, nor the twins were killed. Only Onan was killed as an everlasting testament to the evil of defrauding the marriage of its procreative purpose. Onan was not killed because he did not want to marry Tamar. The punishment for not marrying Tamar ( see Deut 25 ) was not death. If he chose not to marry Tamar, she could remove his sandal and spit in his face publicly, thereby humiliating him. This is much less than the death penalty.
Onan was killed because his action of contraception had far reaching effects and consequences. His action attacked God’s plan for life. Children were supposed to be born who were not born. We see from this account that contraception thwarts God’s plan for life and that God repudiates contraception. God essentially says 'The plan for life and creation is my plan.'