The Prophet ﷺ said, "None of you should wish for death because of a hardship that has befallen him. Rather, let him say, 'Allah, keep me alive as long as life is better for me, and take my soul when death is better for me.'"Ali bin Hujr narrated this to us, saying that Ismail bin Ibrahim informed them, who reported from Abdul-Aziz bin Suhayb, from Anas bin Malik, from the Prophet ﷺ.
وقد روي
عن النبي ﷺ أنه قال لا يتمنين أحدكم الموت لضر نزل به وليقل اللهم أحيني ما كانت الحياة خيرا لي وتوفني إذا كانت الوفاة خيرا لي حدثنا بذلك علي بن حجر أخبرنا إسمعيل بن إبراهيم أخبرنا عبد العزيز بن صهيب عن أنس بن مالك عن النبي ﷺ بذلك
Agreed upon, and Bukhari narrated it in the Book of Supplications, Chapter on supplicating for death and life, no. 6351, and Muslim, no. 2680, from the hadith of Ismail bin Ulaya, through the same route.