swiftcode
swiftcode

Reputation: 3059

How to handle database connection in ASP.NET MVC 4 gracefully?

How do I gracefully handle errors when trying to connect to a database that may be down, or given an incorrect connection string in MVC 4?

I have my string in Web.config and the way it accesses the database is just instantiating my class derived from DBContext in each controller, like so:

private DBEntities db = new DBEntities("database");

This works fine if the database is up and everything is correct, but if it's not, the pages on my web site display this error:

Exception Details: System.ComponentModel.Win32Exception: The network path was not found

Obviously I don't want this to appear, what I'd like to do is have a way to try catch the error and display a custom error page (similar to 404 Page Not Found).

Thank you.

Upvotes: 0

Views: 8869

Answers (3)

paul
paul

Reputation: 22001

start by adding an 'Error.cshtml' view in the Shared views folder. Give it a model type of System.Web.Mvc.HandleErrorInfo

Then add the following to your web.config file

<system.web>
  <customErrors mode="On" defaultRedirect="/Error" />
</system.web>

This will redirect to the Error view on any exception.

Now it's just a matter of styling your error page.

I'd advise you try { } catch { } as suggested in the other posts, in your catch block, just rethrow with a user-friendlier message - like "Database connection could not be made."

Quite a full discussion/explanation here: http://www.prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc

Upvotes: 1

CR41G14
CR41G14

Reputation: 5594

Do the initialisation in the function

private DBEntities db;

// then in your function attempt to initialise
try{

db = new DBEntities("database");

db.Connection.Open();

}
catch(Exception ex){

if(db.Connection != ConnectionState.Closed){

db.Connection.Close();
db.Dispose();

//go to error page
}

}

Upvotes: 1

Paul D&#39;Ambra
Paul D&#39;Ambra

Reputation: 7814

It depends where private DBEntities db = new DBEntities("database"); is and when it is called but why not just:

try {
  private DBEntities db = new DBEntities("database");
} catch (Exception ex) {
  //do something here
}

Upvotes: 1

Related Questions