Sunan an-Nasa'i, Book 21, Hadith 4 (In-Book) ⓘ
It was narrated that Anas said: "The Messenger of Allah said: 'None of you should wish for death because of some harm that befalls him. If he must wish for death, let him say: Allahumma ahini ma kanatil-hayatu khairantli wa tawaffani idha kanatil-wafatu khairanli (O Allah, keep me alive so long as life is good for me, and cause me to die when death is good for me)"
أَخْبَرَنَا عَلِيُّ بْنُ حُجْرٍ، قَالَ حَدَّثَنَا إِسْمَاعِيلُ ابْنُ عُلَيَّةَ، عَنْ عَبْدِ الْعَزِيزِ، ح وَأَنْبَأَنَا عِمْرَانُ بْنُ مُوسَى، قَالَ حَدَّثَنَا عَبْدُ الْوَارِثِ، قَالَ حَدَّثَنَا عَبْدُ الْعَزِيزِ، عَنْ أَنَسٍ، قَالَ قَالَ رَسُولُ اللَّهِ صلى الله عليه وسلم " أَلاَ لاَ يَتَمَنَّى أَحَدُكُمُ الْمَوْتَ لِضُرٍّ نَزَلَ بِهِ فَإِنْ كَانَ لاَ بُدَّ مُتَمَنِّيًا الْمَوْتَ فَلْيَقُلِ اللَّهُمَّ أَحْيِنِي مَا كَانَتِ الْحَيَاةُ خَيْرًا لِي وَتَوَفَّنِي إِذَا كَانَتِ الْوَفَاةُ خَيْرًا لِي " .
also referenced under: Hadith 1821 (Reference) & Volume 3, Book 21, Hadith 1822 (DarusSalam)