Recently I encountered an error saying The type initializer for class threw an exception from a .NET windows service. The error was thrown while accessing any members/methods of a class. The error kept happening until the .NET Windows service was restarted.
After digging deeper into application error logs and analyzing the code in depth, I learnt the below:
The offending class had static variables. One of the static variables was getting initialized by invoking DB repository method to get configured value.private static decimal minInsurancePremuimAmount = InsuranceConfigRepository.GetMinPremuimAmount();
The database repository method was throwing exception when failed to fetch the data from Database Server in case of any transient error,etc.try
// Log and throw the exception
- When the offending class was first accessed, .NET framework tried to initialize the static variables. When it tried to initialize the minInsurancePremuimAmount, it resulted in a SQLException because Database server was not accessible at that time.
So .NET framework could not complete the class initialization logic. Hence application was giving the error until it restarted.
The type initializer threw an exception.
What was the fix?
- So taking clue from the issue, code changed to ensure static members initialization logic will never throw the exception up the call stack. In case of any errors happened during the static members initialization, such Exceptions just eaten and logged for DEBUG purposes.
In the offending class, the internal logic was modified.
Before accessing such static members, the members were NULL checked. If they were still NULL, the code was added to initialize the variable.
This way even if there is an exception, only the current method invocation would fail, but not any future method invocations will result in the error "type initializer threw an exception".