Arduino script stops after random period of time

Thanks for your reply. A very large portion of this ncode comes from www.loveelectronics.co.uk/Tutorials/13/tilt-compensated-compass-arduino-tutorial.
So I cannot speak for the errors in the math. I am very new to Arduino. I have tried to incorporate a retry mecahnism like so

 if (SD.exists("datalog.txt")) {
   
  dataFile.print(RadiansToDegrees(HnTC));
  dataFile.print(", ");   
  dataFile.println(RadiansToDegrees(HTC));
  digitalWrite(runningPin, HIGH);
  delay(250);  
 
  } else if(writeError <= 5) {
    dataFile.print(RadiansToDegrees(HnTC));
    dataFile.print(", ");   
    dataFile.print(RadiansToDegrees(HTC));
    dataFile.print(", Write Error #: ");   
    writeError ++;
    dataFile.println(writeError);
    delay(250);
    
  } else {
    dataFile.flush();
    digitalWrite(failurePin, HIGH); 
    Serial.print(F("Error recording at "));
    Serial.println(recordCount);
    digitalWrite(runningPin, LOW);
    digitalWrite(failurePin, HIGH);
  }

Would this work? It is worth mentioning that currently, when the code goes wrong, the failure light does not illuminate only the Arduinos red power LED is lit up, there is no other activity.

Thanks again for your assistance and patience.