NLog - Throw exception and log message at the same time

Viewed 852

I have the following method which includes a validation check at the beginning. I'm using NLog and I would like to log the exception message and throw the exception 'at the same time', avoiding as much code bloat as possible.

Currently, I do the following, but it seems a bit bulky. Is there a better way?

public static void ValidateValue(string value)
{
    if (!string.IsNullOrWhiteSpace(value) && value.Contains(","))
    {
        ArgumentException ex = new ArgumentException(string.Format("value cannot contain ',': {0}", value));
        Logger.Error(ex);
        throw ex;
    }
}

What I'm looking for would be more along the lines of

public static void ValidateValue(string value)
{
    if (!string.IsNullOrWhiteSpace(value) && value.Contains(","))
        throw Logger.Error<ArgumentException>("value cannot contain ',': {0}", value);
}

where the Logger.Error<> method returns the ArgumentException after it has logged the message.

This seems like something that would be useful and may well already exist, but maybe I have to roll my own extension method?

Thanks!

1 Answers
Related