Within a class I have to following code which occurs several times:
var message = $"My Message with Value1='{value1}' and Value2='{value2}'.";
Log.Error(exception, message);
throw new CustomException(message);
message is always different, but the approach of logging the error and throwing an exception is always the same.
Now both Rider and ReSharper within Visual Studio give the following warning: Message template is not a compile time constant.
I can refactor it into this and the warning goes away:
const string messagePattern = "My Message with Value1='{0}' and Value2='{1}'.";
var messageParameters = new object[] { value1, value2 };
Log.Error(exception, messagePattern, messageParameters);
throw new CustomException(string.Format(messagePattern, messageParameters));
But how can I make this code reusable to avoid that I have to repeat the logging and throwing? This is what I'd like to do:
const string messagePattern = "My Message with Value1='{0}' and Value2='{1}'.";
var messageParameters = new object[] { value1, value2 };
LogAndThrow(exception, messagePattern, messageParameters);
void LogAndThrow(Exception exception, string messagePattern, string messageParameters)
{
Log.Error(exception, messagePattern, messageParameters);
throw new CustomException(string.Format(messagePattern, messageParameters));
}
But this gives the same error because messagePattern is not a const anymore and declaring it as in string messagePattern doesn't help.
Is there any way to make this code reusable except disabling the warning?