Onan's crime was much more specific. IIRC, Mosaic law required that if the eldest son of a family died married but childless, the next-eldest son was required either to try to impregnate the widow (with any resulting child being declared to have been fathered by the deceased, and thus being named heir of the family's estate) or publicly refuse to do so.
Onan was commanded by God to impregnate his brother's widow as the law demanded. He had sex with her, but withdrew before ejaculation so as to avoid impregnating her. His crime was not masturbation (he didn't), nor was it his refusal to have a child of his own (for any child he conceived would not have been his own). Rather, his crime was his secret refusal to give his brother an heir.
To put it another way, Onan was required by God and by law to put his seed to a particular use. That destroying seed which is slated for a particular use is a crime does not mean all 'spilling of seed' is a crime. The general rule is not implied by the highly-specific example.