ProfK
ProfK

Reputation: 51064

Handling a scenario of an unavailable database in an MVC application

In this scenario I wish too bypass my normal error logging, which wont work, and simply request the Error view and and send an email. I don't wish to duplicate this special case handling in all controllers, and DB access might be attempted before any action is requested. Where should I place this special handler, and if not in a controller, how do I call up the Error view?

Oh yes, I'm using Elmah for routine logging of unhandled exceptions.

Upvotes: 0

Views: 143

Answers (2)

Chase Florell
Chase Florell

Reputation: 47397

Try using something along these lines in your controller

[HandleError(ExceptionType = typeof(SqlException), View = "SqlError")]
Public Class ProductController: Controller {
    public ViewResult Item(string itemID)
    {
            Item item = ItemRepository.GetItem(itemID);
            return View(item);
    }
}

Now in your Views/Shared/ folder you can create a View called "SqlError.aspx" that will be returned if there's a SQL Exception.

I would also recommend handling all of your Application Error "stuff" in the Global.asax file. IE: the part that does the emailing of the error, logging of the error, etc.

Check out this SO question for an idea
ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Upvotes: 1

BritishDeveloper
BritishDeveloper

Reputation: 13359

I don't know what you code is but assuming the logging is done in some global error handling thing then edit the error handling to be like this should do it:

try
{
  //logging
}
catch(SqlException)
{
  //send email
  return View("Error");
}

Upvotes: 0

Related Questions