The Messenger of Allah ﷺ said, "None of you should wish for death because of some hardship that has befallen him. If he must wish for it, let him say, 'O Allah, keep me alive so 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 through the route of Ismail bin Ulaya, from Abdul-Aziz bin Suhayb, from Anas, who mentioned it.