The Shulchan Aruch writes (Orach Chayim 222) that one must recite a Beracha upon experiencing misfortune with the same joy and fervor with which one recites a Beracha upon experiencing blessing. He explains that accepting God's harsh decrees with love is an act of Avodat Hashem, service of God, and nothing should make a religious person happier than an opportunity to serve the Almighty. Therefore, even life's misfortunes should be greeted with an element of joy.
The Mishna Berura (commentary to the Shulchan Aruch by Rabbi Yisrael Meir Kagan, the "Chafetz Chayim," Lithuania, 1835-1933) elaborates on this concept of accepting God's harsh decrees with love. In truth, he writes, every misfortune that befalls a person in this world serves to atone for a sin that he has committed, thereby sparing him the punishments of the next world. Punishments in the next world, the Mishna Berura adds, are far more severe than any suffering a person can endure in this world, and therefore misfortunes here on earth are actually beneficial for a person. This notion is often compared to bankruptcy, which allows a bankrupt business to pay just 10 cents to the dollar. Suffering and misfortune in this world works very much the same way; it enables us to erase our "debt" by "paying" much less than we would if the punishment had been delayed until the next world.
The Mishna Berura cites in this context a passage in the Midrash that tells of Yitzchak's request that God bring punishment upon people in this world. Yitzchak understood the gravity of punishment in the next world, and he therefore preferred enduring the punishments in this world. God indeed caused Yitzchak to become blind in his final years, thereby granting his request for suffering during his lifetime.
Several Simanim later (230:5), the Shulchan Aruch writes, "A person should always accustom himself to saying, 'Everything the Almighty does – He does for the best'." The Shulchan Aruch considered it a Halachic imperative to respond to life's hardships with this attitude, acknowledging that somehow it is all to our benefit. He emphasizes that a person must say this "always," even in situations where he does not and cannot understand how a given misfortune is to his benefit. A person is required to live his life with this perspective, and realize that even the painful and difficult experiences we endure actually serve our best interests.