Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5 error handling

We want to handle 403 errors, 404 errors, all errors due to a MySpecialDomainException and provide a default error page for all other errors (including errors in the IIS configuration!). All errors should return proper Razor views, it would be very nice to have an ErrorController in front of the views. E.g. something like this:

public class ErrorController : Controller {     public ViewResult NotFound () { return View(); }     public ViewResult Forbidden () { return View(); }     public ViewResult Default ()     {         var ex = ObtainExceptionFromSomewhere();         if(ex is MySpecialDomainException)             return View("MySpecialDomainException", new ErrorModel { Exception = ex });          return View("GeneralError", new ErrorModel { Exception = ex });     } } 

Currently you find many different ways to do that on the www, some most probably outdated. Among those:

  • Controller.OnException()
  • Error filter
  • customErrors element in web.config
  • Handling in Global.asax's Application_Error

Q1: What is the recommended way to fulfill our requirements with ASP.NET MVC 5?

Also we want to catch errors occurring in the IIS host. Q2: To prevent that IIS has to handle any 404s we thought about adding a default route matching all possible URLs - is this recommendable? Better to register instead for IIS' 404s as well?

Q3: Is it even possible to register an IIS error page which goes back to a controller, or is IIS capable of ASPX / static HTML only?

like image 999
D.R. Avatar asked Feb 24 '14 16:02

D.R.


People also ask

What is global exception handling in MVC?

Another way to handle controller level exceptions is by overriding the OnException() method in the controller class. This method handles all your unhandled errors with error code 500. It allows you to log an exception and redirect to the specific view. It does not require to enable the <customErrors> config in web.

How does ASP.NET handle errors?

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.

Can we use try catch in MVC?

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.


2 Answers

The best way is using Global.Asax, because you can manage all types of errors (Ajax calls/ all of unexpected Errors). with others you can't do it.

Like this:

protected void Application_Error() {     HttpContext httpContext = HttpContext.Current;     if (httpContext != null)     {         RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;         /* When the request is ajax the system can automatically handle a mistake with a JSON response.             Then overwrites the default response */         if (requestContext.HttpContext.Request.IsAjaxRequest())         {             httpContext.Response.Clear();             string controllerName = requestContext.RouteData.GetRequiredString("controller");             IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();             IController controller = factory.CreateController(requestContext, controllerName);             ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);              JsonResult jsonResult = new JsonResult             {                 Data = new { success = false, serverError = "500" },                 JsonRequestBehavior = JsonRequestBehavior.AllowGet             };             jsonResult.ExecuteResult(controllerContext);             httpContext.Response.End();         }         else         {             httpContext.Response.Redirect("~/Error");         }     } } 
like image 143
natnael88 Avatar answered Sep 28 '22 08:09

natnael88


There is no golden solution to all applications.

You can display a friendly error page by using httpErrors in web.config. Unlike customErrors this is an IIS level setting and will even show you a friendly error page for errors which are not from within ASP.NET.

For error logging I would recommend to go with a HttpModule like ELMAH: https://code.google.com/p/elmah/

I wrote a whole blog post about this and where I explain the different ways of error handling: http://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging

like image 26
dustinmoris Avatar answered Sep 28 '22 07:09

dustinmoris