Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Exception Handling Asp.Net Core

Exception Handling Asp.Net Core

Date- Aug 05,2020

Updated Mar 2026

20746

Exception Handling

Error Handling In ASP.Net Core

Error handling in ASP.NET Core has evolved significantly from the traditional ASP.NET MVC framework. In the earlier versions, developers relied on OnException methods to manage exceptions during action execution. However, in ASP.NET Core, the framework has shifted towards a middleware-based approach, which provides more control and flexibility in handling errors and exceptions.

In this article, we will explore how to effectively implement exception handling in ASP.NET Core applications, ensuring that errors are logged appropriately and users receive meaningful feedback. This approach not only improves the developer experience but also enhances the overall user experience by providing clear and concise error messages.

Setting Up Error Logs

In ASP.NET Core, most of the configuration for error handling is done within the Startup.cs file. The Configure method is where we can set up middleware to handle exceptions. Below is a code snippet demonstrating how to configure exception handling to log errors to a separate file.

public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseExceptionHandler(a => a.Run(async context => { var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var exception = exceptionHandlerPathFeature.Error; if (!Directory.Exists(env.ContentRootPath + "\App_Data\log\")) { Directory.CreateDirectory(env.ContentRootPath + "\App_Data\log\"); } var filename = env.ContentRootPath + "\App_Data\" + "log\" + "Logerror.txt"; using (var sw = new System.IO.StreamWriter(filename, true)) { sw.WriteLine(DateTime.Now.ToString() + " " + exception.Message + " " + exception.InnerException + " " + exception.StackTrace); } var result = JsonConvert.SerializeObject(new { error = exception.Message }); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(result); })); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

This code checks if the application is running in a development environment. If so, it sets up an exception handler that logs the exception details to a text file located in the App_Data/log directory. In production, it redirects users to a generic error page.

Custom Error Pages

Providing a user-friendly error page is essential for enhancing the user experience. Instead of showing raw error messages, you can create custom error pages that guide users on what to do next. To set up custom error pages, you can modify the UseExceptionHandler middleware in the Startup.cs file.

app.UseExceptionHandler("/Home/Error");

In the example above, when an error occurs, users will be redirected to the Error action of the HomeController. You can create a view for this action that displays a friendly error message along with any relevant information, such as a link back to the homepage.

Global Exception Handling

In some cases, it may be beneficial to implement global exception handling across your application. This can be achieved by creating a custom middleware component that catches exceptions and logs them accordingly. Here’s an example of how to implement a global exception handler:

public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; public ExceptionHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { await HandleExceptionAsync(context, ex); } } private Task HandleExceptionAsync(HttpContext context, Exception ex) { // Log the exception and create a response here } }

To utilize this middleware, you would add it to the Configure method in your Startup.cs file:

app.UseMiddleware<ExceptionHandlingMiddleware>();

Logging Frameworks

A robust logging framework is essential for effective exception handling. ASP.NET Core supports various logging providers, such as Serilog, NLog, and the built-in logging framework. Integrating a logging library can greatly enhance your application's ability to capture and analyze errors.

For example, to use Serilog with ASP.NET Core, you would first install the necessary NuGet packages and configure it in the Startup.cs file:

public void ConfigureServices(IServiceCollection services) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); services.AddLogging(loggingBuilder => { loggingBuilder.AddSerilog(); }); }

With this setup, all exceptions can be logged to a file, and you can easily adjust the logging level and output format.

Edge Cases & Gotchas

When implementing exception handling, it's important to consider edge cases that may not be immediately apparent. For example, if your application throws exceptions during middleware execution, these exceptions may not be caught by the standard exception handler.

Additionally, ensure that any asynchronous methods properly propagate exceptions. If an exception is thrown in an asynchronous method, it may be caught in a different context than expected. Always use await when calling asynchronous methods to ensure proper exception handling.

Performance & Best Practices

To optimize performance while handling exceptions, consider the following best practices:

  • Use structured logging: This allows you to capture detailed information about exceptions and their context without cluttering your logs with unnecessary text.
  • Avoid excessive logging: While logging is essential, logging too much information can lead to performance issues. Log only what is necessary for diagnosing the problem.
  • Handle known exceptions gracefully: For exceptions that you anticipate, provide user-friendly messages rather than generic error responses.
  • Test exception handling: Implement unit tests to ensure that your exception handling logic works as expected and that errors are logged appropriately.

Conclusion

Effective exception handling is crucial for building reliable ASP.NET Core applications. By implementing custom error pages, utilizing logging frameworks, and considering edge cases, you can significantly enhance the user experience and maintain application stability.

  • Understand the differences: Familiarize yourself with the changes in exception handling between ASP.NET MVC and ASP.NET Core.
  • Implement logging: Use a robust logging framework to capture and analyze exceptions.
  • Provide user-friendly feedback: Ensure that users receive meaningful error messages instead of raw exceptions.
  • Test thoroughly: Regularly test your exception handling logic to catch potential issues early.

S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Mastering File I/O in Java: A Comprehensive Guide to Reading and Writing Files
Mar 16, 2026
Mastering Exception Handling in Java: A Comprehensive Guide
Mar 16, 2026
Mastering Exception Handling in C#: A Comprehensive Guide
Mar 16, 2026
NoSuchwindowException in Java
Aug 31, 2023
Next in ASP.NET Core
Send Email With HTML Template And PDF Using ASP.Net C#

Comments

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 25994 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20234 views
  • How to implement Paypal in Asp.Net Core 19629 views
  • Task Scheduler in Asp.Net core 17531 views
  • Implement Stripe Payment Gateway In ASP.NET Core 16771 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor