Five Methods To Deal with Errors In ASP .Net

Any real-world web application needs a program to handle errors. In ASP.NET Web Forms there are certain events and custom error pages to deal with them. In ASP.NET MVC there is [HandleError] feature, exception filters and custom error pages to deal. In ASP.NET Core there are a set of methods and, exception filters for you. In this blog topic; I will discuss 5 methods for error handling.

These methods are from the Configure() method of the startup class. They are available as extension methods of the IApplicationBuilder object received by the Configure() method. These extension method generally call the Microsoft.AspNetCore.Diagnostics middleware to get the job done.

To view these methods in action, create a new ASP.NET Core application based on Web Application project template. Then open the HomeController and deliberately put an exception from the Index() action as shown below:

public IActionResult Index()

{

throw new Exception(“This is some exception!!!”);

return View();

}

The code above is quite simple and needs no explanation.

Let’s discuss the 5 methods one by one:

1. UseDeveloperExceptionPage() – Looks after exception details during development

The  UseDeveloperExceptionPage() method is very easy during development stage. To use this method open the Startup.cs file, locate the Configure() method and change it to appear like this:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseDeveloperExceptionPage();

….

….

}

As mentioned earlier this method should be used only during development stage as you don’t want to show the details to the end user. That’s why it is a good idea to call UseDeveloperExceptionPage() method like this:

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

else

{

//something else here

}

Now the UseDeveloperExceptionPage() is housed inside an if block. If the hosting environment is development IsDevelopment() method returns true and only then UseDeveloperExceptionPage() gets called. Otherwise some other error handling code take place.

2. UseExceptionHandler() – Gives the control to custom error handler

This method uses a specified error handler to deal with the exception. The error handler logs the exceptions and show a friendly message to the end user. To use this method first of all open the HomeController and locate the Error() action. This action is added as a part of the Web Application project template and also has the corresponding view – Error.cshtml – inside the Views folder.

Change the Error() action as shown below:

public IActionResult Error()

{

var exception = HttpContext.Features

.Get<IExceptionHandlerFeature>();

ViewData["statusCode"] = HttpContext.

Response.StatusCode;

ViewData["message"] = exception.Error.Message;

ViewData["stackTrace"] = exception.

Error.StackTrace;

return View();

}

The Error() action extracts exception details and sends them to the Error view through ViewData. To grab the exception that was thrown the code uses Features.Get() method on HttpContext. The HTTP status code is obtained using the Response.StatusCode property. The status code, exception message and exception stack trace are stored in ViewData dictionary for the use on the Error view.

Now open Error view and change it as shown below:

<h1>@ViewData["message"]</h1>

<h2>Status Code : @ViewData["statusCode"]</h2>

<div>@ViewData["stackTrace"]</div>

The above code is simple enough for any explanation.

Finally, visit the Configure() method and change it to call UseExceptionHandler().

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseExceptionHandler(“/Home/Error”);

….

….

}

As you can see, this time we call UseExceptionHandler() method and specify /Home/Error action as a string parameter. So whenever there is any unhandled exception control will be taken to Error() action.

3. UseStatusCodePages() – This shows error pages for HTTP status codes

The two methods discussed above deal with the unhandled exceptions that arise from your code. But, that’s not the only source of errors. At times errors are generated due to internal server errors, non existent pages, web server authorization issues and so on. These errors are reflected by the HTTP status codes such as 500, 404 and 401.

To deal with these errors you can use UseStatusCodePages() method. This method can be used as follows:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePages();

….

….

}

Although the default version permits us to see the HTTP status code, but it is a plain text. So you can format it as an HTML fragment. You can do that as shown below:

app.UseStatusCodePages(“text/html”,

“<h1>Status code page</h1> <h2>Status Code: {0}</h2>”);

The UseStatusCodePages() method now uses HTML markup to render the status code. Notice the use of {0} to output the status code at a specific place within the markup.

4. UseStatusCodePagesWithRedirects() – Perform URL redirection upon error

Many times you might want to handover the control to some action whenever there is some HTTP error (such as 404). It is then, UseStatusCodePagesWithRedirects() comes handy. It sends HTTP status code 302 (Found) to the browser and performs the redirection using the action specified. Take the following code:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}”);

….

….

}

The code takes UseStatusCodePagesWithRedirects() method and passes /CustomErrorPages/{0} as a string parameter. The {0} placeholder is used only if you wish to pass the status code (such as 404) to the handler. Then sum up another action to the HomeController as shown below:

[Route("/CustomErrorPages/{code}")]

public IActionResult StatusCodeErrors(string code)

{

ViewData["statusCode"] = code;

return View();

}

The [Route] attribute maps /CustomErrorPages to StatusCodeErrors(). The StatusCodeErrors() action accepts code parameter that is the HTTP status code. Make sure to add the StatusCodeErrors view and output the ViewData statusCode value on it.

Note that this response is given by Error view. The {0} placeholder passed 404 to the Error() action. You can conditionally give some different view based on the status code if you so wish. You can also device a mechanism like this:

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}.html”);

You can now see the code redirects to a separate HTML pages stored as 404.html, 500.html and so on. This way you can display different custom error pages for different status codes.

5. UseStatusCodePagesWithReExecute() – Re-execute the request pipeline with alternate action

The UseStatusCodePagesWithReExecute() is similar to UseStatusCodePagesWithRedirects() in that both executes some alternate action if there is any HTTP error. But, UseStatusCodePagesWithRedirects() does redirection to the alternate action whereas UseStatusCodePagesWithReExecute() re-executes the entire request pipeline and executes the alternate action. The UseStatusCodePagesWithRedirects() sends status code of 302 to the browser and browser address bar reflects the new URL upon redirection. In case of UseStatusCodePagesWithReExecute() the original status code is sent to the browser and the address bar will continue to show the original URL.

You can use the UseStatusCodePagesWithReExecute() method as follows :

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithReExecute(“/CustomErrorPages/{0}”);

….

….

}

We conclude the discussion here. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>