Lesson 28 of 40 Architecture Intermediate 40 min

Logging and Error Handling

Learn how logging and error handling work in ASP.NET Core and why they are essential for building stable, reliable, and maintainable applications. Proper handling of errors helps developers diagnose problems and improves the user experience.

Part 1: What Is Logging?

Logging is the process of recording information about what happens inside your application. These records can include normal operations, warnings, and errors.

Logs help developers:

Part 2: What Is Error Handling?

Error handling is the process of managing unexpected situations that occur during program execution. These situations are often called exceptions.

Instead of allowing the application to crash, error handling ensures that:

Part 3: Basic Logging Example

ASP.NET Core includes built-in logging support. A logger can be injected into a controller using Dependency Injection.

private readonly ILogger<StudentController> _logger;

public StudentController(ILogger<StudentController> logger)
{
  _logger = logger;
}

_logger.LogInformation("Student list accessed");

This records information about application activity.

Part 4: Handling Exceptions

In C#, exceptions can be handled using try–catch blocks.

try
{
  // risky operation
}
catch (Exception ex)
{
  _logger.LogError(ex, "An error occurred");
}

This prevents the application from crashing and records the error for debugging.

Part 5: Global Error Handling

ASP.NET Core supports global error handling using middleware. This allows the application to handle all unhandled exceptions in one place.

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

This redirects users to a friendly error page instead of showing technical details.

Part 6: Development vs Production

Error handling should be different depending on the environment.

Environment Behavior
Development Show detailed error information
Production Show user-friendly messages only

This protects sensitive information from being exposed in production systems.

Part 7: Logging in the Student Project

In your Student CRUD application, logging can be used to track important actions:

This helps maintain system reliability and accountability.

Part 8: Best Practices

Good logging and error handling improve both developer productivity and user experience.

Summary

Logging and error handling are essential parts of professional ASP.NET Core development. They help you detect problems, maintain system stability, and create a better experience for users. With proper logging and error handling, your application becomes more reliable and easier to manage.

VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.