The Messenger of Allah ﷺ said, "None of you should wish for death because of some hardship that has befallen him. But if he absolutely must wish for it, then let him say, 'Allah, keep me alive as long as life is better for me, and take me as long as death is better for me.'"
أخبرنا علي بن حجر قال حدثنا إسمعيل ابن علية عن عبد العزيز ح وأنبأنا عمران بن موسى قال حدثنا عبد الوارث قال حدثنا عبد العزيز
قال رسول الله ﷺ ألا لا يتمنى أحدكم الموت لضر نزل به فإن كان لا بد متمنيا الموت فليقل اللهم أحيني ما كانت الحياة خيرا لي وتوفني ما كانت الوفاة خيرا لي
Bukhari narrated it in the chapter on invocations, section on supplicating for death and life, Hadith: 6351, and Muslim, in the chapter on remembrance and supplication, section on the dislike of wishing for death because of harm that has befallen one, Hadith 2680, from the hadith of Ismail bin Ulaya, transmitted through him, and it is in Al-Kubra, Hadith: 1947.