<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net core global handling &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-global-handling/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>Help you to find best ASP.NET Core Hosting</description>
	<lastBuildDate>Fri, 07 Oct 2022 04:30:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net core global handling &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Know Further About Global Error Handling ASP.NET 6</title>
		<link>https://topreviewhostingasp.net/know-further-about-global-error-handling-asp-net-6/</link>
					<comments>https://topreviewhostingasp.net/know-further-about-global-error-handling-asp-net-6/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 07 Oct 2022 04:25:20 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core global handling]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[asp net core web api]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=3235</guid>

					<description><![CDATA[Introduction When we are building our application, although we hope that our application will run without any errors until the end of time. This is not really the case exceptions happens in applications and we need to handle them. Exception Handling is a foundation that we need to consider while we are designing and building [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"><strong>Introduction</strong></h2>



<p>When we are building our application, although we hope that our application will run without any errors until the end of time. This is not really the case exceptions happens in applications and we need to handle them.</p>



<p>Exception Handling is a foundation that we need to consider while we are designing and building our application to have a stable application and avoid application crashes.</p>



<p>There are many ways to implement exception handling while building our applications from a very granular approach to a more generic way.</p>



<p>In this article we will be exploring global exception handling through middleware to catch runtime errors efficiently as per our requirement</p>



<h2 class="wp-block-heading">Code</h2>



<p>The first thing we need to do is to create a new WebApi application</p>



<pre class="wp-block-code"><code>dotnet new webapi -n ErrorManagement
</code></pre>



<p>Now that our application has been created we need to install some packages</p>



<pre class="wp-block-code"><code>dotnet add package Microsoft.EntityFrameworkCore 
dotnet add package Microsoft.EntityFrameworkCore.Design 
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Microsoft.EntityFrameworkCore.Tools</code></pre>



<p>To make sure everything is running as it should we need to build our application</p>



<pre class="wp-block-code"><code>dotnet build
</code></pre>



<p>Now it’s time to add the models, for this sample application we will be creating an app to list all F1 drivers. For this we will create a Models folder in the root directory of our application which will contain our models</p>



<p>Inside the Models folder we will create a new class called Driver</p>



<pre class="wp-block-code"><code>namespace ErrorManagement.Models;
public class Driver
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public int DriverNumber { get; set; }
    public string Team { get; set; } = "";
}</code></pre>



<p>After the model has been created the next step is to create our database db context in the root directory of our application we will create a new folder called Data and inside the Data folder will add the AppDbContext class</p>



<pre class="wp-block-code"><code>using ErrorManagement.Models;
using Microsoft.EntityFrameworkCore;

namespace ErrorManagement.Data;

public class AppDbContext: DbContext
{
    public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options): base(options) {  }

    public DbSet&lt;Driver&gt; Drivers { get; set; }
}</code></pre>



<p>Now we need to add the connection string in the appsettings.json</p>



<pre class="wp-block-code"><code>"ConnectionStrings": {
    "SampleDbConnection": "User ID =jacques;Password=12345678;Server=localhost;Port=3328;Database=sampledb; Integrated Security=true;Pooling=true;"
  }</code></pre>



<p>Next we need to update our program.cs</p>



<pre class="wp-block-code"><code>builder.Services.AddEntityFrameworkNpgsql().AddDbContext&lt;ApiDbContext&gt;(opt =&gt;
        opt.UseNpgsql(builder.Configuration.GetConnectionString("SampleDbConnection")));</code></pre>



<p>Once we add these we can do our migration</p>



<pre class="wp-block-code"><code>dotnet ef migrations add "initial_migration"
dotnet ef database update</code></pre>



<p>Now lets create the DriverServices in the root directory of our application let us create a new folder called Services and inside that folder we will create a new interface called IDriverService</p>



<pre class="wp-block-code"><code>using ErrorManagement.Models;

namespace ErrorManagement.Services;

public interface IDriverService
{
    public Task&lt;IEnumerable&lt;Driver&gt;&gt; GetDrivers();
    public Task&lt;Driver?&gt; GetDriverById(int id);
    public Task&lt;Driver&gt; AddDriver(Driver Driver);
    public Task&lt;Driver&gt; UpdateDriver(Driver Driver);
    public Task&lt;bool&gt; DeleteDriver(int Id);
}</code></pre>



<p>Now inside the same folder we will create a new class called DriverService</p>



<pre class="wp-block-code"><code>using ErrorManagement.Data;
using ErrorManagement.Models;
using Microsoft.EntityFrameworkCore;

namespace ErrorManagement.Services;

public class DriverService : IDriverService
{
    private readonly AppDbContext _dbContext;

    public DriverService(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task&lt;IEnumerable&lt;Driver&gt;&gt; GetDrivers()
    {
        return  await _dbContext.Drivers.ToListAsync();
    }

    public async Task&lt;Driver?&gt; GetDriverById(int id)
    {
        return await _dbContext.Drivers.FirstOrDefaultAsync(x =&gt; x.Id == id);
    }

    public async Task&lt;Driver&gt; AddDriver(Driver Driver)
    {
        var result = _dbContext.Drivers.Add(Driver);
        await _dbContext.SaveChangesAsync();
        return result.Entity;
    }

    public async Task&lt;Driver&gt; UpdateDriver(Driver Driver)
    {
        var result = _dbContext.Drivers.Update(Driver);
        await _dbContext.SaveChangesAsync();
        return result.Entity;
    }

    public async Task&lt;bool&gt; DeleteDriver(int Id)
    {
        var filteredData = _dbContext.Drivers.FirstOrDefault(x =&gt; x.Id == Id);
        var result = _dbContext.Remove(filteredData);
        await _dbContext.SaveChangesAsync();
        return result != null ? true : false;
    }
}</code></pre>



<p>Let us now update our Program.cs so our DriverServices would be injected in our Dependency Inject container</p>



<pre class="wp-block-code"><code>builder.Services.AddScoped&lt;IDriverService, DriverService&gt;();
</code></pre>



<p>Now lets create our DriverController, insider the controller folder we will create a new class called DriversController and will add the following</p>



<pre class="wp-block-code"><code>using ErrorManagement.Models;
using ErrorManagement.Services;
using Microsoft.AspNetCore.Mvc;

namespace ErrorManagement.Controllers;

[ApiController]
[Route("[controller]")]
public class DriversController : ControllerBase
{
    private readonly ILogger&lt;WeatherForecastController&gt; _logger;
    private readonly IDriverService _driverServices;

    public DriversController(
        ILogger&lt;WeatherForecastController&gt; logger,
        IDriverService driverServices)
    {
        _logger = logger;
        _driverServices = driverServices;
    }

    [HttpGet("driverlist")]
    public async Task&lt;IEnumerable&lt;Driver&gt;&gt; DriverList()
    {
        var driverList = await _driverServices.GetDrivers();
        return driverList;
    }

    [HttpGet("getdriverbyid")]
    public async Task&lt;IActionResult&gt; GetDriverById(int Id)
    {
        _logger.LogInformation($"Fetch Driver with ID: {Id} from the database");
        var driver = await _driverServices.GetDriverById(Id);
        if (driver == null)
        {
            //throw new Notfound($"Driver ID {Id} not found.");
            return NotFound();
        }
        _logger.LogInformation($"Returning driver with ID: {driver.Id}.");
        return Ok(driver) ;
    }

    [HttpPost("adddriver")]
    public async Task&lt;IActionResult&gt; AddDriver(Driver driver)
    {
        var result = await _driverServices.AddDriver(driver);
        return Ok(result);
    }

    [HttpPut("updatedriver")]
    public async Task&lt;IActionResult&gt; UpdateDriver(Driver driver)
    {
        var result = await _driverServices.UpdateDriver(driver);
        return Ok(result);
    }

    [HttpDelete("deletedriver")]
    public async Task&lt;bool&gt; DeleteDriver(int Id)
    {
        return await _driverServices.DeleteDriver(Id);
    }
}</code></pre>



<p>Now let us add a new folder called Exceptions which will be utilised to manage all of our exceptions</p>



<p>We will be adding the following exceptions</p>



<pre class="wp-block-code"><code>namespace ErrorManagement.Exceptions;

public class BadRequestException : Exception
{
    public BadRequestException(string message) : base(message)
    { }
}</code></pre>



<pre class="wp-block-code"><code>namespace ErrorManagement.Exceptions;

public class KeyNotFoundException : Exception
{
    public KeyNotFoundException(string message) : base(message)
    { }
}</code></pre>



<pre class="wp-block-code"><code>namespace ErrorManagement.Exceptions;

public class NotFoundException : Exception
{
    public NotFoundException(string message) : base(message)
    { }
}</code></pre>



<pre class="wp-block-code"><code>namespace ErrorManagement.Exceptions;

public class NotImplementedException : Exception
{
    public NotImplementedException(string message) : base(message)
    { }
}</code></pre>



<pre class="wp-block-code"><code>namespace ErrorManagement.Exceptions;

public class UnauthorizedAccessException : Exception
{
    public UnauthorizedAccessException(string message) : base(message)
    { }
}</code></pre>



<p>Now that our exceptions has been added, we need to add a folder to the root directory of our application called configurations where we can build our GlobalErrorHandlingMiddleware</p>



<pre class="wp-block-code"><code>using System.Net;
using System.Text.Json;
using ErrorManagement.Exceptions;

using KeyNotFoundException = ErrorManagement.Exceptions.KeyNotFoundException;
using NotImplementedException = ErrorManagement.Exceptions.NotImplementedException;
using UnauthorizedAccessException = ErrorManagement.Exceptions.UnauthorizedAccessException;

namespace ErrorManagement.Configurations;

public class GlobalErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public GlobalErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        HttpStatusCode status;
        var stackTrace = string.Empty;
        string message;

        var exceptionType = exception.GetType();

        if (exceptionType == typeof(BadRequestException))
        {
            message = exception.Message;
            status = HttpStatusCode.BadRequest;
            stackTrace = exception.StackTrace;
        }
        else if (exceptionType == typeof(NotFoundException))
        {
            message = exception.Message;
            status = HttpStatusCode.NotFound;
            stackTrace = exception.StackTrace;
        }
        else if (exceptionType == typeof(NotImplementedException))
        {
            status = HttpStatusCode.NotImplemented;
            message = exception.Message;
            stackTrace = exception.StackTrace;
        }
        else if (exceptionType == typeof(UnauthorizedAccessException))
        {
            status = HttpStatusCode.Unauthorized;
            message = exception.Message;
            stackTrace = exception.StackTrace;
        }
        else if (exceptionType == typeof(KeyNotFoundException))
        {
            status = HttpStatusCode.Unauthorized;
            message = exception.Message;
            stackTrace = exception.StackTrace;
        }
        else
        {
            status = HttpStatusCode.InternalServerError;
            message = exception.Message;
            stackTrace = exception.StackTrace;
        }

        var exceptionResult = JsonSerializer.Serialize(new { error = message, stackTrace });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)status;

        return context.Response.WriteAsync(exceptionResult);
    }
}</code></pre>



<p>The GlobalErrorHandlingMiddleware is used to provide more control over exceptions which the application will generate</p>



<p>If there is any errors within an incoming request the GlobalErrorHandlingMiddleware will handle the error</p>



<p>Now lets create ApplicationBuilderExtension so we can inject our middleware inside the Services folder</p>



<pre class="wp-block-code"><code>namespace ErrorManagement.Configurations;

public static class ApplicationBuilderExtensions
{
    public static IApplicationBuilder AddGlobalErrorHandler(this IApplicationBuilder applicationBuilder)
        =&gt; applicationBuilder.UseMiddleware&lt;GlobalErrorHandlingMiddleware&gt;();
}</code></pre>



<p>Now let us inject this in the Program.cs</p>



<pre class="wp-block-code"><code>app.AddGlobalErrorHandler();
</code></pre>



<h2 class="wp-block-heading">Conclusion</h2>



<p>You have learned about global error handling in .NET 6 Web Api. Hope you enjoy this tutorial.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/know-further-about-global-error-handling-asp-net-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
