The Messenger of Allah ﷺ said, "None of you should wish for death because of some harm that has befallen him. If he absolutely 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.'"
حدثنا عمران بن موسى حدثنا عبد الوارث بن سعيد حدثنا عبد العزيز بن صهيب
قال رسول الله ﷺ لا يتمنى أحدكم الموت لضر نزل به فإن كان لا بد متمنيا الموت فليقل اللهم أحيني ما كانت الحياة خيرا لي وتوفني إذا كانت الوفاة خيرا لي
[Its chain is sahih]. Abu Dawud narrated it in the Book of Funerals, chapter on the dislike of wishing for death, no. 3108, from the hadith of Abdul-Warith, through this route. And from his hadith, Bukhari narrated it, no. 5671, and Muslim, no. 2680, and others besides them. Thabit also narrated it from Anas through this route, and it is agreed upon (by Bukhari and Muslim).