All Projects → IharYakimush → asp-net-core-exception-handling

IharYakimush / asp-net-core-exception-handling

Licence: MIT License
ASP.NET Core exception handling policies middleware

Programming Languages

C#
18002 projects
powershell
5483 projects

Projects that are alternatives of or similar to asp-net-core-exception-handling

laravel-email-exceptions
Email Exceptions package for Laravel 5.x
Stars: ✭ 33 (-2.94%)
Mutual labels:  exception, exception-handling
demo-serverless-aspnetcore
ASP.Net Core 3.1 on AWS Lambda demo
Stars: ✭ 22 (-35.29%)
Mutual labels:  aspnetcore
BlazorServerWithDocker
Companion code sample for my blog post - Containerising a Blazor Server App
Stars: ✭ 16 (-52.94%)
Mutual labels:  aspnetcore
Home
Asp.net core Mvc Controls Toolkit
Stars: ✭ 33 (-2.94%)
Mutual labels:  aspnetcore
rbac-react-redux-aspnetcore
A starter template for creating JWT token from ASP.NET Core API project and applying that JWT token authentication on React application
Stars: ✭ 54 (+58.82%)
Mutual labels:  aspnetcore
SignalR-Core-SqlTableDependency
Shows how the new SignalR Core works with hubs and sockets, also how it can integrate with SqlTableDependency API.
Stars: ✭ 36 (+5.88%)
Mutual labels:  aspnetcore
DevOpsExamples
A repo to show you how to use a private NuGet feed, such as Telerik, to restore packages in Azure DevOps, GitHub Actions, GitLab CI and AppCenter.
Stars: ✭ 16 (-52.94%)
Mutual labels:  aspnetcore
ChatService
ChatService (SignalR).
Stars: ✭ 26 (-23.53%)
Mutual labels:  aspnetcore
Ark.Tools
Ark set of helper libraries
Stars: ✭ 20 (-41.18%)
Mutual labels:  aspnetcore
AspSqliteCache
An ASP.NET Core IDistributedCache provider backed by SQLite
Stars: ✭ 39 (+14.71%)
Mutual labels:  aspnetcore
OrdersManagementSystem
Project demonstrates usage of Prism composition library, Material design library, SQL Server, Entity Framework in WPF application
Stars: ✭ 29 (-14.71%)
Mutual labels:  aspnetcore
CoreFormatters
.NET Core Custom Formatter for Yaml
Stars: ✭ 21 (-38.24%)
Mutual labels:  aspnetcore
casbin-aspnetcore
Casbin.NET integration and extension for ASP.NET Core
Stars: ✭ 39 (+14.71%)
Mutual labels:  aspnetcore
hk-cache-manager
Simple wrapper for Redis Cache with Stackoverflow.Redis & AspNetCore aim
Stars: ✭ 17 (-50%)
Mutual labels:  aspnetcore
H2PC TagExtraction
A application made to extract assets from cache files of H2v using BlamLib by KornnerStudios.
Stars: ✭ 12 (-64.71%)
Mutual labels:  handling
AspNetCore.Mvc.FluentActions
Fluent Actions for ASP.NET Core MVC are abstractions of regular MVC actions that are converted into MVC actions during startup.
Stars: ✭ 17 (-50%)
Mutual labels:  aspnetcore
BlazorWasmWithDocker
Companion code sample for my blog post - Containerising a Blazor WebAssembly App
Stars: ✭ 16 (-52.94%)
Mutual labels:  aspnetcore
react-redux-aspnet-core-webapi
No description or website provided.
Stars: ✭ 34 (+0%)
Mutual labels:  aspnetcore
blazor-ui
A collection of examples related to Telerik UI for Blazor Components: https://www.telerik.com/blazor-ui
Stars: ✭ 182 (+435.29%)
Mutual labels:  aspnetcore
ex
Exception net
Stars: ✭ 17 (-50%)
Mutual labels:  exception-handling

ASP.NET Core Exception Handling Middleware

ASP.NET Core exception handling policies middleware. Allows to set a chain of exception handlers per exception type. OOTB handlers: log, retry, set responce headers and body

Code Sample

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddExceptionHandlingPolicies(options =>
    {
        options.For<InitializationException>().Rethrow();
                
        options.For<SomeTransientException>().Retry(ro => ro.MaxRetryCount = 2).NextPolicy();
                
        options.For<SomeBadRequestException>()
            .Response(e => 400)
                .Headers((h, e) => h["X-MyCustomHeader"] = e.Message)
				.WithBody((req,sw, exception) =>
                    {
                        byte[] array = Encoding.UTF8.GetBytes(exception.ToString());
                        return sw.WriteAsync(array, 0, array.Length);
                    })
            .NextPolicy();

        // Ensure that all exception types are handled by adding handler for generic exception at the end.
        options.For<Exception>()
            .Log(lo =>
                {
                    lo.LogAction = (l, c, e) => l.LogError(e,"UnhandledException");
                    lo.Category = (context, exception) => "MyCategory";
                })
            .Response(null, ResponseAlreadyStartedBehaviour.GoToNextHandler)
                .ClearCacheHeaders()
                .WithObjectResult((r, e) => new { msg = e.Message, path = r.Path })
            .Handled();
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseExceptionHandlingPolicies();
    app.UseMvc();
}

Policy exception handler transitions

When exception catched in middleware it try to apply handlers from first registered policy suitable for given exception. Policy contains a chain of handlers. Each handler perform some action and apply transition. To prevent re throw of exception handlers chain MUST ends with "Handled" transition. Following handlers currently supported:

Handler Action Transition
Rethrow Apply ReThrow transition ReThrow
NextPolicy Try to execute next policy suitable for given exception NextPolicy
Handled Mark exception as handled to prevent it from bein re thrown Handled
Retry Execute aspnetcore pipeline again if retry count not exceed limit Retry (if retry limit not exceeded) or NextHandler
Log Log exception NextHandler
DisableFurtherLog Prevent exception from being logged again in current middleware (for current request only) NextHandler
Response Modify response (set status code, headers and body) depending on further response builder configuration NextHandler

Sample of transitions: alt text

Nuget

Package Comments
Community.AspNetCore.ExceptionHandling Main functionality
Community.AspNetCore.ExceptionHandling.Mvc Allow to use MVC IActionResult (including ObjectResult) in 'Response' handler
Community.AspNetCore.ExceptionHandling.NewtonsoftJson Allow to set Json serialized object as a response body in 'Response' handler. Use it only if 'Community.AspNetCore.ExceptionHandling.Mvc' usage not possible
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].