Another interpretation of (Genesis 38:2): "And Judah saw there." There is one who committed fornication and profited, and there is one who committed fornication and lost. There is one who stole and profited, and there is one who stole and lost. The one who stole and profited—this is Phinehas. The one who stole and lost—this is Achan. The one who committed fornication and lost—this is Zimri. The one who committed fornication and profited—this is Judah, for from him arose Perez and Hezron, who were destined to raise up David and the Messianic King, who is destined to redeem Israel. See how many devices the Holy One, blessed be He, brought about before He raised up the Messianic King from Judah—that one of whom it is written (Isaiah 11:2): "And the spirit of the LORD shall rest upon him."
Why Judah Profited Where Zimri and Achan Were Lost
Midrash Tanchuma Buber, Vayeshev 13:13
ד"א וירא שם יהודה. יש שנאף ונשכר ויש שנאף והפסיד, יש שגנב ונשכר ויש שגנב והפסיד, יש שגנב ונשכר זה פנחס ונשכר זה פנחס, יש שגנב והפסיד זה עכן, יש שנאף והפסיד זה זמרי, נאף ונשכר זה יהודה שממנו עמדו פרץ וחצרון שהן עתידין להעמיד לדוד ולמלך המשיח, שהוא עתיד לגאול את ישראל ראה כמה עלילות הביא הקב"ה עד שלא העמיד מלך המשיח מיהודה, אותו שכתוב בו ונחה עליו רוח ה' (ישעיה יא ב).