views:

117

answers:

1

If an exception occurs in my MessageHandler I want to write the exception details to my database. How do I do this?

Obviously, I cant just catch the exception, write to database, and rethrow it since NSB rollbacks all changes. (IsTransactional is set to true)

I tried adding logging functionality in a seperate handler, which I caledl using SendLocal if an exception occured, but this does not work:

public void Handle(MessageItem message)
{
    try
    {
        DoWork();
    }
    catch(Exception exc)
    {
        Bus.SendLocal(new ExceptionMessage(exc.Message));
        throw;
    }
}

I also tried using Log4Net with a custom appender, but this also rolled back.

Configure.With()
.Log4Net<DatabaseAppender>(a => a.Log = "Log")

appender:

public class DatabaseAppender : log4net.Appender.AppenderSkeleton
{
    public string Log { get; set; }

    protected override void Append(log4net.Core.LoggingEvent loggingEvent)
    {
        if (loggingEvent.ExceptionObject != null)
            WriteToDatabase(loggingEvent.ExceptionObject);
    }
}

Is there anyway to log unhandled exceptions in the messagehandler when IsTransactional is true?

Thanks in advance.

+1  A: 

I recommend to configure appenders with a configuration file and not in code. This way whoever operates your software can decide how stuff should be logged. The standard AdoNetAppender has the following configuration switch:

<param name="UseTransactions" value="False" />

I think this would work the way you want. If you really want to use your own appender you can either check in log4net source code how they do it. They probably use the TransactionScope class with the TransactionScopeOption.Suppress option.

Stefan Egli
Thanks a million for that. Both ways work perfectly.
IGoor