The Messenger of Allah ﷺ said, "Let none of you wish for death because of some hardship that has befallen him. If one must wish for death, let him say, 'O Allah, keep me alive as long as life is better for me, and take me when death is better for me.'"
قال رسول الله ﷺ: لا يتمنين أحد منكم الموت لضر نزل به، فإن كان لابد متمنيا للموت فليقل: اللهم أحيني ما كانت الحياة خيرا لي، وتوفني إذا كانت الوفاة خيرا لي.
Bukhari narrated it in the Book of Supplications (6351), and Muslim in the Book of Remembrance and Supplication (2680), both from the hadith of Ismail bin Ulaya, from Abdul-Aziz bin Suhayb, from Anas bin Malik, who mentioned it.