The Prophet ﷺ said, "None of you should wish for death because of some harm that has befallen him. If he must do so, let him say, 'O Allah, keep me alive as long as life is better for me, and take my soul when death is better for me.'"
قال النبي ﷺ: لا يتمنين أحدكم الموت من ضر أصابه، فإن كان لا بد فاعلا، فليقل: اللهم أحيني ما كانت الحياة خيرا لي، وتوفني إذا كانت الوفاة خيرا لي.
Bukhari narrated it in the Book of the Sick (5671), and Muslim in the Book of Remembrance and Supplication (2680), both from the hadith of Shubah, from Thabit Bunani, from Anas, who related it.Nawawi said in his commentary on Sahih Muslim, "This contains an explicit statement that it is disliked to wish for death because of harm that has befallen one, whether from illness, poverty, or the persecution of an enemy, or similar worldly hardships. But if one fears harm to his religion or fears being subjected to trial in it, there is no dislike in that, based on the implication of this hadith and others. Many of the early generations did this second thing when they feared trial in their religion."It also shows that if someone fears this and cannot bear his condition in his trial through illness or the like, he should say, 'O Allah, keep me alive if life is better for me...' though the more excellent course is patience and calm submission to the divine decree."