Ibn Dinar, the freed slave of the family of Zubayr, reported from Salim bin Abdullah bin Umar, from Ibn Umar, from Umar, that the Messenger of Allah ﷺ said, "Whoever sees someone afflicted with a trial and says, 'Praise be to Allah who has spared me from what He has tested you with and favored me greatly over many of those He has created,' will be protected from that affliction, whatever it may be, for as long as he lives."
حدثنا محمد بن عبد الله بن بزيع حدثنا عبد الوارث بن سعيد
و بن دينار مولى آل الزبير عن سالم بن عبد الله بن عمر عن ابن عمر عن عمر أن رسول الله ﷺ قال من رأى صاحب بلاء فقال الحمد لله الذي عافاني مما ابتلاك به وفضلني على كثير ممن خلق تفضيلا إلا عوفي من ذلك البلاء كائنا ما كان ما عاش
[Its chain is daif] Ibn Majah also recorded it in the Book of Supplication, chapter on what a man should say when he sees someone afflicted, hadith no. 3892, from the hadith of Amr bin Dinar, the steward of the household of Zubayr, in abbreviated form, and he is daif. The hadith has daif corroborating narrations, one of which is the following hadith.There is also a narration on this topic from Abu Hurairah [to come: 3432].