{"id":2007,"date":"2024-11-02T22:51:10","date_gmt":"2024-11-02T20:51:10","guid":{"rendered":"https:\/\/epicmarketing.co.il\/notebook\/?p=2007"},"modified":"2024-11-02T23:09:41","modified_gmt":"2024-11-02T21:09:41","slug":"error-handling-and-logging","status":"publish","type":"post","link":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/","title":{"rendered":"Error Handling and Logging"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Learning Objectives<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Understand how to implement <strong>global error handling<\/strong> using middleware in ASP.NET Core.<\/li>\n\n\n\n<li>Learn how to create a consistent <strong>error response format<\/strong> for better client-side debugging.<\/li>\n\n\n\n<li>Learn how to use the <strong>built-in logging system<\/strong> in ASP.NET Core, as well as integrate <strong>third-party logging providers<\/strong> like <strong>Serilog<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Global Exception Handling<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What is Global Exception Handling?<\/strong> <strong>Global exception handling<\/strong> allows you to catch and handle errors that occur anywhere in your application. It is essential to prevent unexpected crashes and to ensure that the user receives meaningful error messages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In ASP.NET Core, you can implement global exception handling using <strong>middleware<\/strong> to provide a consistent response format for all unhandled exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Why Use Middleware for Error Handling?<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Middleware can handle exceptions globally instead of managing them in individual controllers or services.<\/li>\n\n\n\n<li>It provides a consistent response format for clients and prevents the server from leaking sensitive information.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Global Error Handling Middleware<\/strong>:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Create Custom Middleware for Error Handling<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class ErrorHandlingMiddleware\n{\n    private readonly RequestDelegate _next;\n\n    public ErrorHandlingMiddleware(RequestDelegate next)\n    {\n        _next = next;\n    }\n\n    public async Task InvokeAsync(HttpContext context)\n    {\n        try\n        {\n            await _next(context);\n        }\n        catch (Exception ex)\n        {\n            await HandleExceptionAsync(context, ex);\n        }\n    }\n\n    private Task HandleExceptionAsync(HttpContext context, Exception ex)\n    {\n        context.Response.ContentType = &quot;application\/json&quot;;\n        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;\n\n        var response = new { message = &quot;An unexpected error occurred.&quot;, details = ex.Message };\n        return context.Response.WriteAsync(JsonSerializer.Serialize(response));\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Register Middleware in <code>Program.cs<\/code><\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar app = builder.Build();\n\napp.UseMiddleware&lt;ErrorHandlingMiddleware&gt;();\n\napp.UseRouting();\napp.UseAuthorization();\napp.MapControllers();\napp.Run();\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Explanation<\/strong>: The <code>ErrorHandlingMiddleware<\/code> catches any unhandled exceptions, sets the appropriate status code, and returns a JSON response with an error message. This provides a consistent error format for all clients.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In an <strong>e-commerce<\/strong> application, when something goes wrong (e.g., unable to add an item to the cart due to a database issue), the global error handler provides a structured error response, avoiding the app crashing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Logging<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What is Logging?<\/strong> <strong>Logging<\/strong> involves recording information about your application\u2019s runtime behavior. Logs are crucial for debugging and troubleshooting, especially for tracking errors and understanding how users interact with the system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Built-in Logging System in ASP.NET Core<\/strong>: ASP.NET Core provides a built-in logging framework that works with various logging providers (e.g., Console, Debug).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Using Built-in Logging in a Controller<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.Extensions.Logging;\n\n&#x5B;ApiController]\n&#x5B;Route(&quot;api\/products&quot;)]\npublic class ProductController : ControllerBase\n{\n    private readonly ILogger&lt;ProductController&gt; _logger;\n\n    public ProductController(ILogger&lt;ProductController&gt; logger)\n    {\n        _logger = logger;\n    }\n\n    &#x5B;HttpGet(&quot;{id}&quot;)]\n    public IActionResult GetProduct(int id)\n    {\n        _logger.LogInformation(&quot;Getting product with ID: {ProductId}&quot;, id);\n\n        if (id &lt;= 0)\n        {\n            _logger.LogWarning(&quot;Invalid product ID: {ProductId}&quot;, id);\n            return BadRequest(&quot;Invalid product ID.&quot;);\n        }\n\n        try\n        {\n            \/\/ Simulate fetching product logic\n            return Ok(new { Id = id, Name = &quot;Laptop&quot;, Price = 1200 });\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, &quot;Error occurred while getting product with ID: {ProductId}&quot;, id);\n            return StatusCode(500, &quot;Internal server error&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Explanation<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>LogInformation<\/strong>: Logs informational messages (e.g., tracking a specific action).<\/li>\n\n\n\n<li><strong>LogWarning<\/strong>: Logs a warning for situations that are not errors but could lead to problems.<\/li>\n\n\n\n<li><strong>LogError<\/strong>: Logs error details, typically when an exception is caught.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In a <strong>financial application<\/strong>, logging can be used to track each transaction made by a user to understand what actions took place before an error occurred.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Integrating Third-Party Logging: Serilog<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>What is Serilog?<\/strong> <strong>Serilog<\/strong> is a popular third-party logging library for .NET that provides rich features like <strong>structured logging<\/strong> and the ability to write logs to various destinations, such as files, databases, and cloud logging platforms.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>How to Integrate Serilog<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Install Serilog NuGet Packages<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Install <code>Serilog.AspNetCore<\/code> and <code>Serilog.Sinks.File<\/code> via NuGet.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Configure Serilog in <code>Program.cs<\/code><\/strong>:<\/li>\n<\/ol>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Serilog;\n\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.Console()\n    .WriteTo.File(&quot;logs\/log.txt&quot;, rollingInterval: RollingInterval.Day)\n    .CreateLogger();\n\nvar builder = WebApplication.CreateBuilder(args);\nbuilder.Host.UseSerilog();\n\nvar app = builder.Build();\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Example: Logging with Serilog<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class ProductService\n{\n    private readonly ILogger&lt;ProductService&gt; _logger;\n\n    public ProductService(ILogger&lt;ProductService&gt; logger)\n    {\n        _logger = logger;\n    }\n\n    public void AddProduct(Product product)\n    {\n        try\n        {\n            _logger.LogInformation(&quot;Adding a new product: {ProductName}&quot;, product.Name);\n            \/\/ Add product logic here\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, &quot;Error occurred while adding product: {ProductName}&quot;, product.Name);\n            throw;\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Explanation<\/strong>: Serilog provides enhanced logging capabilities, such as writing log data to files, which can help with debugging and auditing actions in the system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: In a <strong>user management system<\/strong>, when an admin adds or deletes a user, Serilog logs this information to a file, which can be reviewed for audit purposes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Examples<\/strong><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Logging in a Controller Action<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Log when an endpoint is accessed and if it fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;HttpGet(&quot;get-all&quot;)]\npublic IActionResult GetAllProducts()\n{\n    _logger.LogInformation(&quot;Getting all products.&quot;);\n    try\n    {\n        \/\/ Simulate fetching all products\n        return Ok(new List&lt;string&gt; { &quot;Product1&quot;, &quot;Product2&quot; });\n    }\n    catch (Exception ex)\n    {\n        _logger.LogError(ex, &quot;Failed to get all products.&quot;);\n        return StatusCode(500, &quot;Internal server error.&quot;);\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: Logs when users access the list of products in an e-commerce site.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Middleware-Based Error Handling<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Create a middleware to handle unhandled exceptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic async Task InvokeAsync(HttpContext context)\n{\n    try\n    {\n        await _next(context);\n    }\n    catch (Exception ex)\n    {\n        _logger.LogError(ex, &quot;Unhandled exception occurred.&quot;);\n        context.Response.StatusCode = 500;\n        await context.Response.WriteAsync(&quot;An unexpected error occurred.&quot;);\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: Handles unexpected errors while processing payments in a <strong>financial transaction<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Simple Example: Using Serilog to Log to a File<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Write logs to a file for persistent storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Code Snippet<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nLog.Logger = new LoggerConfiguration()\n    .WriteTo.File(&quot;logs\/errors.txt&quot;, rollingInterval: RollingInterval.Day)\n    .CreateLogger();\n\n_logger.LogInformation(&quot;Application started and logging initialized.&quot;);\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Real-Life Example<\/strong>: Logs user activities in a <strong>user management<\/strong> system to track who added or removed users.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Takeaways<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Global Exception Handling<\/strong>: Use middleware to provide a consistent error-handling mechanism across your application.<\/li>\n\n\n\n<li><strong>Logging<\/strong>: Use built-in ASP.NET Core logging to track the behavior of your system and capture issues.<\/li>\n\n\n\n<li><strong>Third-Party Logging with Serilog<\/strong>: Serilog allows you to log information to different sinks like console, files, and databases for easier debugging and auditing.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Practical Questions<\/strong><\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>What are the benefits of using <strong>global exception handling<\/strong>?<\/li>\n\n\n\n<li>How can <strong>Serilog<\/strong> enhance logging in a .NET application compared to the built-in logger?<\/li>\n\n\n\n<li>How would you implement a consistent error response format across all your API endpoints?<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>New Concepts in .NET 8<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>New in .NET 8<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Improved Logging Configuration<\/strong>: .NET 8 makes configuring logging in the <code>Program.cs<\/code> file more streamlined, reducing boilerplate code while keeping flexibility.<\/li>\n\n\n\n<li><strong>Exception Middleware Improvements<\/strong>: The built-in exception middleware has been enhanced to provide <strong>better performance<\/strong> and easier integration for handling complex error scenarios.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">E-commerce program example<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Code Overview<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Global Exception Handling Middleware<\/strong>: Differentiates between general exceptions and SQL database exceptions.<\/li>\n\n\n\n<li><strong>Built-in ASP.NET Core Logging<\/strong>: Logs user activities, including user details, visited pages, products added to the cart, and products purchased.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 1: Configure Built-in Logging in <code>Program.cs<\/code><\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The built-in ASP.NET Core logger is available by default.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar builder = WebApplication.CreateBuilder(args);\n\n\/\/ Configure logging in `Program.cs` (optional)\nbuilder.Logging.ClearProviders(); \/\/ Optional, to start fresh with only selected providers\nbuilder.Logging.AddConsole();     \/\/ Add Console Logging\nbuilder.Logging.AddDebug();       \/\/ Add Debug Logging\n\nbuilder.Services.AddControllers();\nbuilder.Services.AddScoped&lt;IProductRepository, ProductRepository&gt;();\n\nvar app = builder.Build();\n\napp.UseMiddleware&lt;ErrorHandlingMiddleware&gt;();\n\napp.UseRouting();\napp.UseAuthorization();\napp.MapControllers();\n\napp.Run();\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>AddConsole<\/strong> and <strong>AddDebug<\/strong>: Use the default built-in providers to write logs to the console and debug output.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 2: Create Global Error Handling Middleware<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The middleware will handle exceptions and differentiate between general and SQL database exceptions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing System.Data.SqlClient;\nusing Microsoft.Extensions.Logging;\n\npublic class ErrorHandlingMiddleware\n{\n    private readonly RequestDelegate _next;\n    private readonly ILogger&lt;ErrorHandlingMiddleware&gt; _logger;\n\n    public ErrorHandlingMiddleware(RequestDelegate next, ILogger&lt;ErrorHandlingMiddleware&gt; logger)\n    {\n        _next = next;\n        _logger = logger;\n    }\n\n    public async Task InvokeAsync(HttpContext context)\n    {\n        try\n        {\n            await _next(context);\n        }\n        catch (SqlException sqlEx)\n        {\n            _logger.LogError(sqlEx, &quot;Database connection error occurred.&quot;);\n            context.Response.StatusCode = 500;\n            await context.Response.WriteAsync(&quot;A database error occurred. Please try again later.&quot;);\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, &quot;An unexpected error occurred.&quot;);\n            context.Response.StatusCode = 500;\n            await context.Response.WriteAsync(&quot;An unexpected error occurred. Please contact support.&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Logging for Exceptions<\/strong>: The middleware catches <strong>SQL exceptions<\/strong> separately from <strong>general exceptions<\/strong>, logs both, and returns appropriate responses.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 3: Create Product Controller<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>ProductController<\/strong> manages user actions, such as viewing products, adding products to the cart, and purchasing products, with appropriate logging.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.Logging;\n\n&#x5B;ApiController]\n&#x5B;Route(&quot;api\/products&quot;)]\npublic class ProductController : ControllerBase\n{\n    private readonly IProductRepository _productRepository;\n    private readonly ILogger&lt;ProductController&gt; _logger;\n\n    public ProductController(IProductRepository productRepository, ILogger&lt;ProductController&gt; logger)\n    {\n        _productRepository = productRepository;\n        _logger = logger;\n    }\n\n    &#x5B;HttpGet(&quot;{id}&quot;)]\n    public IActionResult GetProduct(int id)\n    {\n        _logger.LogInformation(&quot;User visited product page with ID: {ProductId}&quot;, id);\n\n        var product = _productRepository.GetProductById(id);\n        if (product == null)\n        {\n            _logger.LogWarning(&quot;Product with ID: {ProductId} not found&quot;, id);\n            return NotFound(&quot;Product not found.&quot;);\n        }\n\n        return Ok(product);\n    }\n\n    &#x5B;HttpPost(&quot;add-to-cart\/{id}&quot;)]\n    public IActionResult AddToCart(int id)\n    {\n        _logger.LogInformation(&quot;User added product with ID: {ProductId} to the cart&quot;, id);\n        \/\/ Simulate adding product to the cart\n        return Ok($&quot;Product with ID: {id} added to the cart.&quot;);\n    }\n\n    &#x5B;HttpPost(&quot;purchase\/{id}&quot;)]\n    public IActionResult PurchaseProduct(int id)\n    {\n        try\n        {\n            _logger.LogInformation(&quot;User purchased product with ID: {ProductId}&quot;, id);\n            \/\/ Simulate purchasing the product\n            return Ok($&quot;Product with ID: {id} purchased successfully.&quot;);\n        }\n        catch (SqlException sqlEx)\n        {\n            _logger.LogError(sqlEx, &quot;Failed to purchase product due to database issue.&quot;);\n            return StatusCode(500, &quot;A database error occurred. Please try again later.&quot;);\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, &quot;Failed to purchase product due to an unexpected error.&quot;);\n            return StatusCode(500, &quot;An unexpected error occurred. Please contact support.&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Logging<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Logs when users visit a product page, add a product to the cart, and purchase a product.<\/li>\n\n\n\n<li>Logs warning messages when products are not found.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 4: Create Product Repository<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The repository interacts with the <strong>database<\/strong>. Here, we're simulating the database logic with potential SQL exceptions.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing System.Data.SqlClient;\n\npublic interface IProductRepository\n{\n    Product GetProductById(int productId);\n}\n\npublic class ProductRepository : IProductRepository\n{\n    public Product GetProductById(int productId)\n    {\n        \/\/ Mocking database interaction. In a real application, this would involve a database call.\n        if (productId &lt;= 0)\n        {\n            throw new SqlException(&quot;Invalid product ID&quot;);\n        }\n\n        return new Product { Id = productId, Name = &quot;Product&quot; + productId, Price = 99.99m };\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Simulated Database Logic<\/strong>: Throws an SQL exception when an invalid product ID is provided.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 5: Create Product Model<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Define a <code>Product<\/code> model to represent products in the system.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\npublic class Product\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public decimal Price { get; set; }\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Logging Output<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The logs generated by the <strong>built-in ASP.NET Core logging system<\/strong> can be output to the console and the <strong>Debug<\/strong> window in Visual Studio. Here is what typical log messages might look like:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\ninfo: ProductController&#x5B;0]\n      User visited product page with ID: 1\nwarn: ProductController&#x5B;0]\n      Product with ID: 999 not found\ninfo: ProductController&#x5B;0]\n      User added product with ID: 1 to the cart\ninfo: ProductController&#x5B;0]\n      User purchased product with ID: 1\nerror: ErrorHandlingMiddleware&#x5B;0]\n      Database connection error occurred. SqlException: Invalid product ID\nerror: ErrorHandlingMiddleware&#x5B;0]\n      An unexpected error occurred. Exception: NullReferenceException...\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Summary<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Global Exception Handling<\/strong>: Implemented via custom middleware to differentiate between <strong>general exceptions<\/strong> and <strong>SQL exceptions<\/strong>.<\/li>\n\n\n\n<li><strong>Built-in Logging System<\/strong>: Logs various user activities such as viewing products, adding products to the cart, and purchasing products.<\/li>\n\n\n\n<li><strong>Product Controller<\/strong>: Manages user actions with logging to track each step.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Saving logs to file<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Option 1: Using an Existing Simple File Logger Package<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There is a simple community-built file logging provider that can be used for .NET Core, like <strong>FileLoggerExtensions<\/strong>. Below is how to use it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Add FileLoggerExtensions NuGet Package<\/strong>:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>Configure File Logging in <code>Program.cs<\/code><\/strong>: Once the package is installed, you can configure it in your program to write to a file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar builder = WebApplication.CreateBuilder(args);\n\n\/\/ Configure logging\nbuilder.Logging.ClearProviders(); \/\/ Optional: Clear default providers\nbuilder.Logging.AddConsole();     \/\/ Console logging\nbuilder.Logging.AddDebug();       \/\/ Debug window logging\nbuilder.Logging.AddFile(&quot;logs\/ecommerce_log.txt&quot;); \/\/ File logging\n\nbuilder.Services.AddControllers();\nbuilder.Services.AddScoped&lt;IProductRepository, ProductRepository&gt;();\n\nvar app = builder.Build();\n\napp.UseMiddleware&lt;ErrorHandlingMiddleware&gt;();\n\napp.UseRouting();\napp.UseAuthorization();\napp.MapControllers();\n\napp.Run();\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>AddFile(&quot;logs\/ecommerce_log.txt&quot;)<\/strong>: Configures logging to write log messages to a file named <code>ecommerce_log.txt<\/code> in the <code>logs<\/code> folder.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Option 2: Creating a Custom File Logger<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If you want more control over how logging works, you can <strong>create your own file logger<\/strong>. This involves creating a custom implementation of <code>ILogger<\/code> and <code>ILoggerProvider<\/code>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 1: Create a Custom File Logger<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>FileLogger<\/code> will implement the <code>ILogger<\/code> interface and write logs to a file.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.Extensions.Logging;\nusing System.IO;\n\npublic class FileLogger : ILogger\n{\n    private readonly string _filePath;\n    private static readonly object _lock = new object();\n\n    public FileLogger(string filePath)\n    {\n        _filePath = filePath;\n    }\n\n    public IDisposable BeginScope&lt;TState&gt;(TState state) =&gt; null;\n\n    public bool IsEnabled(LogLevel logLevel) =&gt; logLevel &gt;= LogLevel.Information;\n\n    public void Log&lt;TState&gt;(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func&lt;TState, Exception, string&gt; formatter)\n    {\n        if (!IsEnabled(logLevel))\n            return;\n\n        var logRecord = $&quot;{DateTime.UtcNow.ToString(&quot;yyyy-MM-dd HH:mm:ss&quot;)} &#x5B;{logLevel}] {formatter(state, exception)}&quot;;\n        lock (_lock)\n        {\n            File.AppendAllText(_filePath, logRecord + Environment.NewLine);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Log Method<\/strong>: Formats the log entry and writes it to the specified log file.<\/li>\n\n\n\n<li><strong>Thread-Safe Logging<\/strong>: The lock (<code>_lock<\/code>) ensures that only one thread can write to the file at a time.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 2: Create a File Logger Provider<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A provider is responsible for creating instances of the <code>FileLogger<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.Extensions.Logging;\n\npublic class FileLoggerProvider : ILoggerProvider\n{\n    private readonly string _filePath;\n\n    public FileLoggerProvider(string filePath)\n    {\n        _filePath = filePath;\n    }\n\n    public ILogger CreateLogger(string categoryName)\n    {\n        return new FileLogger(_filePath);\n    }\n\n    public void Dispose() { }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\"><strong>CreateLogger Method<\/strong>: Creates an instance of <code>FileLogger<\/code> for each category.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 3: Add Custom File Logger Extension<\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Add an extension method to easily add the <code>FileLoggerProvider<\/code> to the logging configuration.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\n\npublic static class FileLoggerExtensions\n{\n    public static ILoggingBuilder AddFile(this ILoggingBuilder builder, string filePath)\n    {\n        builder.Services.AddSingleton&lt;ILoggerProvider&gt;(new FileLoggerProvider(filePath));\n        return builder;\n    }\n}\n<\/pre><\/div>\n\n\n<h4 class=\"wp-block-heading\"><strong>Step 4: Configure the Custom File Logger in <code>Program.cs<\/code><\/strong><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Use the new file logger extension in your application.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nvar builder = WebApplication.CreateBuilder(args);\n\n\/\/ Configure logging\nbuilder.Logging.ClearProviders(); \/\/ Optional: Clear default providers\nbuilder.Logging.AddConsole();     \/\/ Console logging\nbuilder.Logging.AddDebug();       \/\/ Debug window logging\nbuilder.Logging.AddFile(&quot;logs\/ecommerce_log.txt&quot;); \/\/ Custom file logging\n\nbuilder.Services.AddControllers();\nbuilder.Services.AddScoped&lt;IProductRepository, ProductRepository&gt;();\n\nvar app = builder.Build();\n\napp.UseMiddleware&lt;ErrorHandlingMiddleware&gt;();\n\napp.UseRouting();\napp.UseAuthorization();\napp.MapControllers();\n\napp.Run();\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 5: Updated Product Controller with Logging<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The controller will log user activities such as viewing products, adding products to the cart, and purchasing products.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\nusing Microsoft.AspNetCore.Mvc;\n\n&#x5B;ApiController]\n&#x5B;Route(&quot;api\/products&quot;)]\npublic class ProductController : ControllerBase\n{\n    private readonly IProductRepository _productRepository;\n    private readonly ILogger&lt;ProductController&gt; _logger;\n\n    public ProductController(IProductRepository productRepository, ILogger&lt;ProductController&gt; logger)\n    {\n        _productRepository = productRepository;\n        _logger = logger;\n    }\n\n    &#x5B;HttpGet(&quot;{id}&quot;)]\n    public IActionResult GetProduct(int id)\n    {\n        _logger.LogInformation(&quot;User visited product page with ID: {ProductId}&quot;, id);\n\n        var product = _productRepository.GetProductById(id);\n        if (product == null)\n        {\n            _logger.LogWarning(&quot;Product with ID: {ProductId} not found&quot;, id);\n            return NotFound(&quot;Product not found.&quot;);\n        }\n\n        return Ok(product);\n    }\n\n    &#x5B;HttpPost(&quot;add-to-cart\/{id}&quot;)]\n    public IActionResult AddToCart(int id)\n    {\n        _logger.LogInformation(&quot;User added product with ID: {ProductId} to the cart&quot;, id);\n        \/\/ Simulate adding product to the cart\n        return Ok($&quot;Product with ID: {id} added to the cart.&quot;);\n    }\n\n    &#x5B;HttpPost(&quot;purchase\/{id}&quot;)]\n    public IActionResult PurchaseProduct(int id)\n    {\n        try\n        {\n            _logger.LogInformation(&quot;User purchased product with ID: {ProductId}&quot;, id);\n            \/\/ Simulate purchasing the product\n            return Ok($&quot;Product with ID: {id} purchased successfully.&quot;);\n        }\n        catch (SqlException sqlEx)\n        {\n            _logger.LogError(sqlEx, &quot;Failed to purchase product due to database issue.&quot;);\n            return StatusCode(500, &quot;A database error occurred. Please try again later.&quot;);\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, &quot;Failed to purchase product due to an unexpected error.&quot;);\n            return StatusCode(500, &quot;An unexpected error occurred. Please contact support.&quot;);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Log File Output<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <strong>custom file logger<\/strong> or <strong>community-built file logger<\/strong> will generate a log file (<code>logs\/ecommerce_log.txt<\/code>) similar to:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: bash; title: ; notranslate\" title=\"\">\n2024-10-30 10:00:00 &#x5B;Information] User visited product page with ID: 1\n2024-10-30 10:01:00 &#x5B;Information] User added product with ID: 1 to the cart\n2024-10-30 10:02:00 &#x5B;Information] User purchased product with ID: 1\n2024-10-30 10:03:00 &#x5B;Error] Failed to purchase product due to database issue. SqlException: Invalid product ID\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Summary<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Built-in Logging System with File Logging<\/strong>: We used the built-in logging capabilities of ASP.NET Core and added a <strong>file logger<\/strong> to save logs to a specific file.<\/li>\n\n\n\n<li><strong>Custom Middleware<\/strong>: Differentiates between general exceptions and SQL database exceptions.<\/li>\n\n\n\n<li><strong>User Activity Logging<\/strong>: Logged when users visited product pages, added products to the cart, and purchased products.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Learning Objectives Global Exception Handling What is Global Exception Handling? Global exception handling allows you to catch and handle errors that occur anywhere in your application. It is essential to prevent unexpected crashes and to ensure that the user receives meaningful error messages. In ASP.NET Core, you can implement global exception handling using middleware to [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[79],"tags":[],"class_list":["post-2007","post","type-post","status-publish","format-standard","hentry","category-dotnet-8","entry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Error Handling and Logging - Code Notebook<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/\" \/>\n<meta property=\"og:locale\" content=\"he_IL\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Error Handling and Logging - Code Notebook\" \/>\n<meta property=\"og:description\" content=\"Learning Objectives Global Exception Handling What is Global Exception Handling? Global exception handling allows you to catch and handle errors that occur anywhere in your application. It is essential to prevent unexpected crashes and to ensure that the user receives meaningful error messages. In ASP.NET Core, you can implement global exception handling using middleware to [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Notebook\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-02T20:51:10+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-02T21:09:41+00:00\" \/>\n<meta name=\"author\" content=\"kerendanino\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u05e0\u05db\u05ea\u05d1 \u05e2\u05dc \u05d9\u05d3\" \/>\n\t<meta name=\"twitter:data1\" content=\"kerendanino\" \/>\n\t<meta name=\"twitter:label2\" content=\"\u05d6\u05de\u05df \u05e7\u05e8\u05d9\u05d0\u05d4 \u05de\u05d5\u05e2\u05e8\u05da\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 \u05d3\u05e7\u05d5\u05ea\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/\"},\"author\":{\"name\":\"kerendanino\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/person\\\/195dfc625818eadda7903d456890e24c\"},\"headline\":\"Error Handling and Logging\",\"datePublished\":\"2024-11-02T20:51:10+00:00\",\"dateModified\":\"2024-11-02T21:09:41+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/\"},\"wordCount\":1310,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\"},\"articleSection\":[\"Dotnet 8\"],\"inLanguage\":\"he-IL\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/\",\"name\":\"Error Handling and Logging - Code Notebook\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#website\"},\"datePublished\":\"2024-11-02T20:51:10+00:00\",\"dateModified\":\"2024-11-02T21:09:41+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/#breadcrumb\"},\"inLanguage\":\"he-IL\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/error-handling-and-logging\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Error Handling and Logging\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#website\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\",\"name\":\"Code Notebook\",\"description\":\"Easy coding\",\"publisher\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"he-IL\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#organization\",\"name\":\"Code Notebook\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"he-IL\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo-epic-marketing-05.png\",\"contentUrl\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/wp-content\\\/uploads\\\/2023\\\/07\\\/logo-epic-marketing-05.png\",\"width\":3626,\"height\":1942,\"caption\":\"Code Notebook\"},\"image\":{\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/logo\\\/image\\\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/#\\\/schema\\\/person\\\/195dfc625818eadda7903d456890e24c\",\"name\":\"kerendanino\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"he-IL\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g\",\"caption\":\"kerendanino\"},\"url\":\"https:\\\/\\\/epicmarketing.co.il\\\/notebook\\\/author\\\/kerendanino\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Error Handling and Logging - Code Notebook","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/","og_locale":"he_IL","og_type":"article","og_title":"Error Handling and Logging - Code Notebook","og_description":"Learning Objectives Global Exception Handling What is Global Exception Handling? Global exception handling allows you to catch and handle errors that occur anywhere in your application. It is essential to prevent unexpected crashes and to ensure that the user receives meaningful error messages. In ASP.NET Core, you can implement global exception handling using middleware to [&hellip;]","og_url":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/","og_site_name":"Code Notebook","article_published_time":"2024-11-02T20:51:10+00:00","article_modified_time":"2024-11-02T21:09:41+00:00","author":"kerendanino","twitter_card":"summary_large_image","twitter_misc":{"\u05e0\u05db\u05ea\u05d1 \u05e2\u05dc \u05d9\u05d3":"kerendanino","\u05d6\u05de\u05df \u05e7\u05e8\u05d9\u05d0\u05d4 \u05de\u05d5\u05e2\u05e8\u05da":"3 \u05d3\u05e7\u05d5\u05ea"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/#article","isPartOf":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/"},"author":{"name":"kerendanino","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/person\/195dfc625818eadda7903d456890e24c"},"headline":"Error Handling and Logging","datePublished":"2024-11-02T20:51:10+00:00","dateModified":"2024-11-02T21:09:41+00:00","mainEntityOfPage":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/"},"wordCount":1310,"commentCount":0,"publisher":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization"},"articleSection":["Dotnet 8"],"inLanguage":"he-IL","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/","url":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/","name":"Error Handling and Logging - Code Notebook","isPartOf":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#website"},"datePublished":"2024-11-02T20:51:10+00:00","dateModified":"2024-11-02T21:09:41+00:00","breadcrumb":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/#breadcrumb"},"inLanguage":"he-IL","potentialAction":[{"@type":"ReadAction","target":["https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/epicmarketing.co.il\/notebook\/error-handling-and-logging\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/epicmarketing.co.il\/notebook\/"},{"@type":"ListItem","position":2,"name":"Error Handling and Logging"}]},{"@type":"WebSite","@id":"https:\/\/epicmarketing.co.il\/notebook\/#website","url":"https:\/\/epicmarketing.co.il\/notebook\/","name":"Code Notebook","description":"Easy coding","publisher":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/epicmarketing.co.il\/notebook\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"he-IL"},{"@type":"Organization","@id":"https:\/\/epicmarketing.co.il\/notebook\/#organization","name":"Code Notebook","url":"https:\/\/epicmarketing.co.il\/notebook\/","logo":{"@type":"ImageObject","inLanguage":"he-IL","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/logo\/image\/","url":"https:\/\/epicmarketing.co.il\/notebook\/wp-content\/uploads\/2023\/07\/logo-epic-marketing-05.png","contentUrl":"https:\/\/epicmarketing.co.il\/notebook\/wp-content\/uploads\/2023\/07\/logo-epic-marketing-05.png","width":3626,"height":1942,"caption":"Code Notebook"},"image":{"@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/epicmarketing.co.il\/notebook\/#\/schema\/person\/195dfc625818eadda7903d456890e24c","name":"kerendanino","image":{"@type":"ImageObject","inLanguage":"he-IL","@id":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/285cc9389c66aa46da1e26a474b1e90e9efaf3fa21f1b928cbd63ce5f0e89c63?s=96&d=mm&r=g","caption":"kerendanino"},"url":"https:\/\/epicmarketing.co.il\/notebook\/author\/kerendanino\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/2007","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/comments?post=2007"}],"version-history":[{"count":4,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/2007\/revisions"}],"predecessor-version":[{"id":2013,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/posts\/2007\/revisions\/2013"}],"wp:attachment":[{"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/media?parent=2007"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/categories?post=2007"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/epicmarketing.co.il\/notebook\/wp-json\/wp\/v2\/tags?post=2007"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}