0

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.

3 Answers 3

1

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
}

}
Sign up to request clarification or add additional context in comments.

Comments

1

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
}

2 Comments

Yes, that seems good but I have one line of that per controller, so I think it's best to place that code in a function somewhere and instantiate it when needed.
Ah, definitely look into injecting an interface into your controllers rather than instantiating your DBEntities in the controllers themselves. I use Ninject but there're many, many more to choose from...
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.