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.
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.
Build Your Agile Team