The Messenger of Allah ﷺ said, "None of you should wish for death because of some hardship that has befallen him. Rather, 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.'"
حدثنا بشر بن هلال حدثنا عبد الوارث عن عبد العزيز بن صهيب
قال رسول الله ﷺ لا يدعون أحدكم بالموت لضر نزل به ولكن ليقل اللهم أحيني ما كانت الحياة خيرا لي وتوفني إذا كانت الوفاة خيرا لي
Its isnad is sahih. Ibn Majah narrated it in Zuhd, chapter "Mention of death and preparing for it," no. 4265, from the hadith of Abdul-Warith bin Saeed. Bukhari, no. 6351, and Muslim, no. 2680, narrated it from the hadith of Abdul-Aziz bin Suhayb, through the same chain.