Bulugh al-Maram 533
Anas (RAA) narrated that the Messenger of Allah (ﷺ) said:
"None of you should wish for death due to any affliction, which might have affected him. But if he feels compelled to wish for it (due to extreme distress that he feels he cannot bear), he should say: “O Allah! Grant me life as long as life is better for me, and let me die when death is better for me.” Agreed upon.
وَعَنْ أَنَسٍ ‏- رضى الله عنه ‏- قَالَ: قَالَ رَسُولُ اَللَّهِ ‏- صلى الله عليه وسلم ‏-{ لَا يَتَمَنَّيَنَّ أَحَدُكُمُ اَلْمَوْتَ لِضُرٍّ يَنْزِلُ بِهِ, فَإِنْ كَانَ لَا بُدَّ مُتَمَنِّيًا فَلْيَقُلْ: اَللَّهُمَّ أَحْيِنِي مَا كَانَتِ اَلْحَيَاةُ خَيْرًا لِي, وَتَوَفَّنِي إِذَا كَانَتِ اَلْوَفَاةُ خَيْرًا لِي }  مُتَّفَقٌ عَلَيْهِ  1‏ .‏‏1 ‏- صحيح.‏ رواه البخاري (5671)‏، ومسلم (2680)‏.‏