Best practice question for error handling in C#?
In our system we will be writing out files, and with each file they will have a corresponding error file. The error file will get written every time even if there are not any errors.
I'm looking at the best way to handle the errors for this. Assuming when we go to write the main CSV file, we would get a number of errors. From permissions on the folder, to a parsing exception when turning a Datatable to a CSV.
If we get a permission error the error log file will fail as well. Would this be done in the exception? in another try catch (which would be bad.. I think).
We would also want to get the exception to place in the error file.
Some pseudo code below (without the try catch in the exception) or should this be broken down more and using methods, that contain their own Try / Catch that could bubble up the messages to log and write to files.
Message.log("begin writing file");
try {
try {
// get data from DB
// write to CSV file
// all good, write Empty Error Log file and main file
}
catch(Exception ex) {
// Write Error File with ex.toCSV
// write log message.
Message.log("error : " + ex.ToString());
}
} catch (Exception ex) {
var e = new Exception(string.Format("An unexpected error occurred for file.\r\n{0}", ex.Message));
Message.log(e);
throw e.
}
Message.log("all files written");