"And his father wept for him" (Genesis 37:35). What is written after it? "And the Medanites sold him into Egypt" (Genesis 37:36). The Holy One, blessed be He, said to Judah: You have no children, and therefore you do not know what the grief over children is. You misled your father and said to him, "Your son is dead." By your life, you shall take a wife and bury your sons, so that you may know the grief over children. What is written after it? "And it came to pass at that time, etc." (Genesis 38:1). And it is written, "And Er and Onan died" (Genesis 46:12). And all those years that Joseph was away from his father, the mind of Jacob was upon Judah. From where do you learn it? From Benjamin, for Judah said to Joseph, "For your servant became surety for the lad" (Genesis 44:32). And once he set his mind upon Benjamin and Joseph made himself known, Judah was found innocent, as it is said, "And the jealousy of Ephraim shall depart, etc." (Isaiah 11:13). Therefore, "And Judah he sent before him, etc." (Genesis 46:28).
Why Judah Buried His Sons for Deceiving Jacob About Joseph
Midrash Tanchuma Buber, Vayigash 10:3
ויבך אותו אביו (שם לז לה), מה כתיב אחריו, והמדנים מכרו אותו אל מצרים (שם שם לו), אמר הקב"ה ליהודה אין לך בנים, לכך אין אתה יודע מה צערן של בנים, והטעיתה את אביך ואמרת לו מת בנך, חייך שתטול אשה ותקבור את בניך, כדי שתדע צערן של בנים, מה כתב אחריו, ויהי בעת ההיא וגו' (בראשית לח א), וכתיב וימת ער ואונן (שם מו יב), וכל אותן השנים שהיה יוסף חוץ מאביו היה דעתו של יעקב על יהודה, מנין אתה למד מבנימן, שאמר יהודה ליוסף כי עבדך ערב את הנער (שם מד לב), וכיון שנתן דעתו על בנימן ונתוודע יוסף, נמצא יהודה נקי, שנאמר וסרה קנאת אפרים וגו', לכך ואת יהודה שלח לפניו וגו'.