Day 15 – Error Handling & Logging Best Practices in .NET Projects

Format: Tutorial + flow diagrams + project-based examples + best practices


Introduction

Error handling and logging are critical components of any professional application. Proper error handling ensures graceful degradation and better user experience, while logging provides insights into application behavior, debugging, and monitoring.

At CuriosityTech.in, learners gain hands-on experience implementing robust error handling and structured logging in ASP.NET Core applications, preparing them for real-world FullStack projects.


1. Understanding Error Handling in .NET

Types of Errors:

Error TypeDescriptionExample
Compile-timeErrors detected during compilationMissing semicolon, type mismatch
RuntimeErrors during executionNullReferenceException, DivideByZero
LogicIncorrect program logicWrong calculation, incorrect query

Best Practices:

  • Always catch exceptions at the appropriate layer

  • Use specific exception types instead of catch(Exception)

  • Avoid exposing internal exceptions to end users

Hierarchical diagram


2. Try-Catch-Finally Block

try

{

    var course = dbContext.Courses.First(c => c.Id == 1);

}

catch (InvalidOperationException ex)

{

    // Handle specific exception

    logger.LogError(ex, “Course not found.”);

}

catch (Exception ex)

{

    // Handle generic exception

    logger.LogError(ex, “An unexpected error occurred.”);

}

finally

{

    // Optional cleanup

}

Explanation:

  • Try: Code that may fail

  • Catch: Handle exceptions gracefully

  • Finally: Cleanup resources like database connections


3. Global Error Handling with Middleware

ASP.NET Core allows centralized error handling:

app.UseExceptionHandler(errorApp =>

{

    errorApp.Run(async context =>

    {

        context.Response.StatusCode = 500;

        context.Response.ContentType = “application/json”;

        var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();

        if(exceptionHandlerPathFeature != null)

        {

            var error = new { Message = “An error occurred.”, Detail = exceptionHandlerPathFeature.Error.Message };

            await context.Response.WriteAsJsonAsync(error);

        }

    });

});

Benefits:

  • Consistent error responses

  • Avoids repetitive try-catch in controllers

  • Easier to log all exceptions centrally


4. Logging in ASP.NET Core

ASP.NET Core provides built-in logging via ILogger<T>.

public class CourseService : ICourseService

{

    private readonly ILogger<CourseService> _logger;

    public CourseService(ILogger<CourseService> logger)

    {

        _logger = logger;

    }

    public void AddCourse(Course course)

    {

        try

        {

            // Add course logic

            _logger.LogInformation(“Course {CourseName} added successfully.”, course.Name);

        }

        catch(Exception ex)

        {

            _logger.LogError(ex, “Error adding course {CourseName}”, course.Name);

            throw;

        }

    }

}

Log Levels:

LevelDescription
TraceDetailed diagnostic information
DebugDebug-level messages
InformationNormal application flow
WarningNon-critical issues
ErrorRecoverable errors
CriticalSystem failure

5. Infographic Idea

6. Real-World Project: CuriosityTech Course Portal

  • Scenario: Track course creation, enrollment, and errors

  • Logging: Use ILogger to track actions and exceptions

  • Error Handling: Global middleware ensures user-friendly messages

  • Benefits:

    • Faster debugging

    • Monitoring production issues

    • Maintain professional-grade applications

7. Best Practices

  • Use structured logging for better insights

  • Avoid logging sensitive data (passwords, tokens)

  • Log exceptions as close as possible to the source

  • Integrate with monitoring tools (Serilog, Seq, ELK Stack)

  • Use try-catch sparingly—don’t swallow exceptions silently


8. CuriosityTech.in Mentorship Insights

  • Step-by-step guidance for implementing error handling and logging

  • Hands-on projects like secure course portal with robust logging

  • Prepares learners for production-ready FullStack applications


Conclusion

Effective error handling and logging are essential for building reliable, maintainable, and professional .NET applications. Using try-catch blocks, global middleware, and ILogger, developers can capture and diagnose errors efficiently. With CuriosityTech.in mentorship, learners gain practical experience that mirrors real-world enterprise standards.

The next step is Day 16 – CI/CD for .NET Full Stack Developers with Azure DevOps, focusing on automating builds, deployments, and delivery pipelines.


Leave a Comment

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