×

iFour Logo

Handling Errors in ASP.Net Core 3.1

Kapil Panchal - November 02, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Handling Errors in ASP.Net Core 3.1

Dealing with errors is a common factor you would face in any kind of application development, no matter what language you have used for the development. Being one of the frequently used frameworks in many.Net Core web development companies, the Asp.Net Core provides fabulous supportfor Error Handling strategies.

Before diving into the core part of the subject, it is highly recommended to have a basic understanding ofconcepts like C#, Asp.Net Core programming, OOPs concepts, Exception handling, try, catch, throw, finally, etc.

Now let us discuss a few approaches related to Error handling in Asp.Net Core 3.1.

Developer Exception Page


It is very important to get notified on-screen about the request exceptions that arise while implementing a web application. Therefore, in order to enable the page while running an application in the Development environment (one of the environment variables used to determine Runtime Environment), you need to add the below code in the Startup.Configure method.

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
              

This Exception page would include the crucial information related to exceptions and request such as: Cookies, QueryString parameters if available, Headers, Stack trace.

 

Exception Handler Page


to configure the custom error handling page for the production environment, you can use Exception Handling In case if you aim Middleware. This middleware performs the following operations:

  • It will catch the exception and makes a log of it.

  • It re-executes the request in the alternate pipeline of a page or controller that is indicated.

The Razor page app template provides thePages folder which is included with Error page with .cshtml extension and an ErrorModel class called “PageModel Class”.

Whereas in the MVC app, the project template would be included with an Error view and an Error action method. You can notice the Error Action method in the below source code.

[AllowAnonymous]
public IActionResultError()
{
  return View(new ErrorViewModel
  { 
    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier 
  });
}
              

Important note:It is recommended not to use Http attributes like Httpget on error handler method, as it could prevent some requests from reaching the method. Therefore, it is better to use Allow Anonymous so that every user including unauthenticated users can also able to see the error view.

 

Accessing the Exception


In order to access the exception, Microsoft has included an interface called IExceptionHandlerPathFeature. It could be used to access the original request path in an error handler controller or page.For Example:

varexceptionHandlerPathFeature =HttpContext.Features.Get();
if (exceptionHandlerPathFeature?.Error is FileNotFoundException)
{
  ExceptionMessage = "File error thrown";
}
if (exceptionHandlerPathFeature?.Path == "/index")
{
  ExceptionMessage += " from home page";
}
                

Use Status Code Pages


This is to alert you that in the Asp.Net Core app, you could not find by-default status code pages like 404-Not Found, etc. The app returns status code with the empty response body.

We can use middleware called UseStatusCodePagesin order to display the status code pages for an app.

As discussed above, we need to call UseStatusCodePages in Startup.Configure method as shown below so that default text-only handlers could get enabled and displayed.

app.UseStatusCodePages();
              

You could see the text output displayed by default handlers like this below:

Status Code: 404; Not Found
              

Use Status Code Pages with Format string


We can also customize the response content type and content text as per our needs. This is done by using the overload of UseStatusCodePages() method that accepts content type and string format.

Example:

app.UseStatusCodePages("text/plain", "Status code page, status code: {0}");
              

Important points to consider about Exception Handling


  • It is often a great idea to include pure static content in the Production Error Pages. It could be helpful while throwing exceptionsin exception handling pages.

  • Once the response headers are sent, the application cannot alter the response’s status codes.

  • Once the response headers are sent, no exception pages or handlers can be run. For doing so you may need to abort the connection.

  • Asp.Net Core application is executed with an in-process HTTP server implementation. This server can handle a few exceptions.

  • 500- Internal Server Error: This response would be sent by the server if it catches the exception before the response headers were sent.

  • If the exception is caught by the server just after the response headers are sent, then the server closes the connection. Remember the requests are handled by the server, not by the app.

Apart from these let us also have a look at some essential topics related to error handling.

Looking to Hire ASP.Net Core Developer ? Contact Now.

Try-catch block error handling

The Error-handling at the code level could be handled using Try-catch block statements. To talk about the rules of utilization, the statement should contain a try block with one or more catch block statements that help in specifying different exceptions. Basically, CLR handles the exception bycrawling over the catch blocks,when the statement throws the exception.

Custom middleware for error handling

Custom_middleware

You can also handle the errors by customizing the Exception Handler Middleware and create custom responses while error occurrences in the middleware pipeline. Have a look at the above image for a detailed overview.

Startup exception handling mechanism

If any error occurs while app startup, then those errors would be handled by none other than the hosting layer itself. You can also configure the host to capture the details of the error occurrence.

Database Error Page

With the assistance of entity framework migrations, you can resolve database-related exceptions that are captured through Database Error Page Middleware. When the error is triggered then an HTML response page would get displayed that consists of possible actions of error-resolving.

Exception Filters

MVC apps provide fabulous support for exception filters to trap the exceptions. These filters can be configured globally, or based on the action or controller basis.

Conclusion


To sum up, these above are the essentials one needs to understand about Handling Errors in ASP.Net Core 3.1. This would be highly beneficial for the developers because there is no such application development environment where you cannot find or face the errors.

Handling Errors in ASP.Net Core 3.1 Dealing with errors is a common factor you would face in any kind of application development, no matter what language you have used for the development. Being one of the frequently used frameworks in many.Net Core web development companies, the Asp.Net Core provides fabulous supportfor Error Handling strategies. Before diving into the core part of the subject, it is highly recommended to have a basic understanding ofconcepts like C#, Asp.Net Core programming, OOPs concepts, Exception handling, try, catch, throw, finally, etc. Now let us discuss a few approaches related to Error handling in Asp.Net Core 3.1. Developer Exception Page It is very important to get notified on-screen about the request exceptions that arise while implementing a web application. Therefore, in order to enable the page while running an application in the Development environment (one of the environment variables used to determine Runtime Environment), you need to add the below code in the Startup.Configure method. if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } This Exception page would include the crucial information related to exceptions and request such as: Cookies, QueryString parameters if available, Headers, Stack trace. Read More: Performing Globalization And Localization Using Resource File In .net Core   Exception Handler Page to configure the custom error handling page for the production environment, you can use Exception Handling In case if you aim Middleware. This middleware performs the following operations: It will catch the exception and makes a log of it. It re-executes the request in the alternate pipeline of a page or controller that is indicated. The Razor page app template provides thePages folder which is included with Error page with .cshtml extension and an ErrorModel class called “PageModel Class”. Whereas in the MVC app, the project template would be included with an Error view and an Error action method. You can notice the Error Action method in the below source code. [AllowAnonymous] public IActionResultError() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } Important note:It is recommended not to use Http attributes like Httpget on error handler method, as it could prevent some requests from reaching the method. Therefore, it is better to use Allow Anonymous so that every user including unauthenticated users can also able to see the error view.   Accessing the Exception In order to access the exception, Microsoft has included an interface called IExceptionHandlerPathFeature. It could be used to access the original request path in an error handler controller or page.For Example: varexceptionHandlerPathFeature =HttpContext.Features.Get(); if (exceptionHandlerPathFeature?.Error is FileNotFoundException) { ExceptionMessage = "File error thrown"; } if (exceptionHandlerPathFeature?.Path == "/index") { ExceptionMessage += " from home page"; } Use Status Code Pages This is to alert you that in the Asp.Net Core app, you could not find by-default status code pages like 404-Not Found, etc. The app returns status code with the empty response body. We can use middleware called UseStatusCodePagesin order to display the status code pages for an app. As discussed above, we need to call UseStatusCodePages in Startup.Configure method as shown below so that default text-only handlers could get enabled and displayed. app.UseStatusCodePages(); You could see the text output displayed by default handlers like this below: Status Code: 404; Not Found Use Status Code Pages with Format string We can also customize the response content type and content text as per our needs. This is done by using the overload of UseStatusCodePages() method that accepts content type and string format. Example: app.UseStatusCodePages("text/plain", "Status code page, status code: {0}"); Important points to consider about Exception Handling It is often a great idea to include pure static content in the Production Error Pages. It could be helpful while throwing exceptionsin exception handling pages. Once the response headers are sent, the application cannot alter the response’s status codes. Once the response headers are sent, no exception pages or handlers can be run. For doing so you may need to abort the connection. Asp.Net Core application is executed with an in-process HTTP server implementation. This server can handle a few exceptions. 500- Internal Server Error: This response would be sent by the server if it catches the exception before the response headers were sent. If the exception is caught by the server just after the response headers are sent, then the server closes the connection. Remember the requests are handled by the server, not by the app. Apart from these let us also have a look at some essential topics related to error handling. Looking to Hire ASP.Net Core Developer ? Contact Now. See here Try-catch block error handling The Error-handling at the code level could be handled using Try-catch block statements. To talk about the rules of utilization, the statement should contain a try block with one or more catch block statements that help in specifying different exceptions. Basically, CLR handles the exception bycrawling over the catch blocks,when the statement throws the exception. Custom middleware for error handling You can also handle the errors by customizing the Exception Handler Middleware and create custom responses while error occurrences in the middleware pipeline. Have a look at the above image for a detailed overview. Startup exception handling mechanism If any error occurs while app startup, then those errors would be handled by none other than the hosting layer itself. You can also configure the host to capture the details of the error occurrence. Database Error Page With the assistance of entity framework migrations, you can resolve database-related exceptions that are captured through Database Error Page Middleware. When the error is triggered then an HTML response page would get displayed that consists of possible actions of error-resolving. Exception Filters MVC apps provide fabulous support for exception filters to trap the exceptions. These filters can be configured globally, or based on the action or controller basis. Conclusion To sum up, these above are the essentials one needs to understand about Handling Errors in ASP.Net Core 3.1. This would be highly beneficial for the developers because there is no such application development environment where you cannot find or face the errors.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...