It is narrated from Sayyiduna Anas bin Malik (may Allah be pleased with him) that the Messenger of Allah (peace and blessings be upon him) said: "Let none of you wish for death because of some harm that has befallen him. If he must do so, then let him say: 'Allahumma ahyini ma kanat al-hayatu khayran li, wa tawaffani idha kanat al-wafatu khayran li' (O Allah, keep me alive as long as life is better for me, and cause me to die when death is better for me)."
Hadith Referenceالسنن الكبرى للبيهقي / كتاب الجنائز / 6565