I'm looking for a standard way to handle errors in asp.net mvc 2.0 or 3.0
You can handle default errors at the application level either by modifying your application's configuration or by adding an Application_Error handler in the Global. asax file of your application. You can handle default errors and HTTP errors by adding a customErrors section to the Web. config file.
We have try catch block for error handling, But in case of MVC we have exception filters. In such case we can handle errors at filter level. i.e. by using exception filters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With