1

I am initializing FluentNHibernate from Application_Start event like so:

Fluently.Configure()
.Database(OracleDataClientConfiguration.Oracle10
            .Driver<NHibernate.Driver.OracleDataClientDriver>()
            .ConnectionString("MyConnectionString")
            .DefaultSchema("MySchema")
        )
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<SomeClass>())
.BuildConfiguration()
.BuildSessionFactory();

If the connection string is bad, or connection to the DB fails for some other reason, I get a TNS No listener exception. I would like to display/log this exception but Application_Start (and Applicaiton_Error) doesn't have an HttpContext or Response object in IIS7 Integrated mode. The user gets a yellow screen of death telling them to turn custom errors On. Elmah doesn't log the message either. I would like to solve the problem in one of two possible ways:

  1. Disable nhibernate configuration from connecting to the database on configuration.
  2. Provide custom user feedback based on the error and get Elmah working (somehow). This would be my ideal choice.

I was able to move NHibernate configuration to run on Session_Start, as described here, which gets exception handling working for this error, but then I get other exceptions that can be misleading to the root cause of the problem. Does anyone have a good solution for this scenario?

Thank you.

Community
  • 1
  • 1
Alex
  • 9,250
  • 11
  • 70
  • 81

1 Answers1

2

This is what I do:

void Application_Start() {
    try {
          // setup your app / nhibernate
    } catch(Exception ex) {
        Application["StartupError"] = ex
    }
}

void Application_BeginRequest() {
    var startupError = Application["StartupError"] as Exception;
    if (startupError != null)
        throw new Exception("Error starting application", startupError);
}

In your BeginRequest method you have access to the Request and can do what you want to show the error (or show a nice page)

Martin Ernst
  • 5,629
  • 2
  • 17
  • 14
  • I get `Exception has been thrown by the target of an invocation.` exception after throwing in `Application_BeginRequest` – Alex Sep 13 '12 at 16:37
  • Well the point is that in BeginRequest you WILL have access to the Request so you can display the error (I throw it and have my own error handling code that either shows a horrible error message in dev, or a pretty error screen in production) – Martin Ernst Sep 14 '12 at 07:53