1

I'd like to be able to put a try/catch around SqlCommand.ExecuteReader and the like, so that I can catch ADO exceptions and log the offending query with better information than is contained in the exception that gets thrown by NH. I've tried to get there in various ways, like overriding SqlClientDriver to return my own version of SqlCommand, but between the fact that the interface changed with NH5 to using DbCommand rather than IDbCommand (so I can't use a proxy) and the fact that SqlCommand itself is sealed (so I can't use a subclass), I've been stymied.

To be clear: I don't want to simply translate the exception. I want all the information about the original query in hand wherever I catch it.

Thanks.

Michael
  • 1,351
  • 1
  • 11
  • 25
  • The same as you did (were going to do) with the `IDbCommand`. Just subclass from `DbCommand` instead of the interface. – hazzik Jan 10 '19 at 09:36
  • But DbCommand has some abstract methods and I have no idea how I should implement them. SqlCommand has implementations but is sealed. – Michael Jan 11 '19 at 07:11

1 Answers1

1

Exception thrown by NHibernate includes the query itself. I am not sure what "all the information" means.

Other alternative is to log the generated SQL using Log4Net:

Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders();

FileAppender fileAppender = new FileAppender();
fileAppender.Name = "NHFileAppender";
fileAppender.File = config.LogFilePath;
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
fileAppender.Layout = new PatternLayout("%d{yyyy-MM-dd HH:mm:ss}:%m%n%n");
fileAppender.ActivateOptions();

Logger logger = hierarchy.GetLogger("NHibernate.SQL") as Logger;
logger.Additivity = false;
logger.Level = Level.Debug;
logger.AddAppender(fileAppender);

hierarchy.Configured = true;

This logs both success and failed statements. You can play with PatternLayout aand GetLogger to get additional information about query.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
  • You're correct -- I was conflating two different issues that I've had. Regarding logging the query I developed a mechanism similar to what you wrote here, but which only dumps the last query before the exception was thrown. If you're interested, I posted it here: https://stackoverflow.com/questions/42888947/how-to-get-sql-with-parameter-values-on-an-exception. I want to improve on that, though, by only doing the logging when the query throws an exception (the current way logs each query but throws the others out). For that I want to surround the query-execution with a try/catch. – Michael Jan 11 '19 at 07:18