The Messenger of Allah ﷺ said, "When Allah tests a Muslim servant with an affliction in his body, Allah says, 'Record for him the righteous deeds he used to perform.' If He restores him to health, He washes him clean and purifies him, and if He takes his soul, He forgives him and shows him mercy."
قال رسول الله ﷺ: إذا ابتلى الله العبد المسلم ببلاء في جسده، قال الله: اكتب له صالح عمله الذي كان يعمله، فإن شفاه غسله وطهره، وإن قبضه غفر له ورحمه.
Imam Ahmad (12503) and Abu Yaala (4233) both narrated it from the hadith of Hammad bin Salama, from Sinan bin Rabia, from Anas, mentioning something similar. Haythami said in Majma(2/304), "Abu Yaala and Ahmad narrated it, and its narrators are trustworthy."I say, its chain of transmission is hasan because of Sinan bin Rabia Bahili Basri, Abu Rabia, for his hadith is hasan. Bukhari cited him paired with another narrator.