I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0
- 404 error handler
- Controller scope exception error handler
- Global scope exception error handler
I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0
For controller scope errors try using a custom Exception attribute i.e.
public class RedirectOnErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
// Don't interfere if the exception is already handled
if(filterContext.ExceptionHandled)
return;
//.. log exception and do appropriate redirects here
}
}
Then decorate the controllers with the attribute and error handling should be yours
[RedirectOnError]
public class TestController : Controller
{
//.. Actions etc...
}
Doesn't help if the error is with the routing though - i.e. it can't find a controller in the first place. For that try the Application Error handler in Global.asax i.e.
protected void Application_Error(object sender, EventArgs e)
{
//.. perhaps direct to a custom error page is here
}
I don't know if it's 'best practice' though. Does work.
Not sure about best practices and depending on what you want to do with the error, would a simple solution not be to use the customErrors setting in the web.config file?
For catching unhandled errors I sometimes make use of the Application_Error method in the Global.asax file.
Also, Take a look at this SO post
Here is the most detailed answer to "404" part of your question. Despite the main topic of that is 404 it would give you an idea about how to apply that to other error types.
Although, I can't state it clearly as the "best practice" since you'll need a layer supertype controller with that approach. I'd better catch those HttpException
s in Global.asax
. But for the most part it is a great guide.
As for arbitrary exceptions throughout your MVC-app - don't forget about HandleErrorAttribute
.