Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

c# exception middleware

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.EventIdFactory = (c, e) => new EventId(123, "UnhandlerException");
                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();
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: convert xml to json 
Csharp :: Default property value in C# 
Csharp :: c# code examples 
Csharp :: create dropdown in datatable c# dynamically 
Csharp :: ado stands for 
Csharp :: camelCase and snakeCase 
Csharp :: math.pow in C# using loop 
Csharp :: symfony debug bar 
Csharp :: combined 2 arrays 
Csharp :: how to auto format c# code in visual studio 
Csharp :: change canvas color uwp c# 
Csharp :: how to get the dynamic year for your web app in mvc 
Csharp :: c# generate insert statement from object 
Csharp :: How do I call a string inside a different class 
Csharp :: list equals in order c# 
Csharp :: c# create default instance of type 
Csharp :: <link rel="stylesheet" href="styles/kendo.common.min.css" / 
Csharp :: c# linq sorting sequential guids 
Csharp :: how to change the color of a textbox with button c# 
Csharp :: how to cut image from timeline editor in c# 
Csharp :: "using" c# 
Csharp :: parse error message: could not create type webservice.webservice asp .net 
Csharp :: how to use display attibute .net core 
Csharp :: Zxing Xamarin use front Camera 
Csharp :: how to show enum name list from input in swagger c# 
Csharp :: finding holydays asp.net 
Csharp :: ${1##*[! ]} 
Csharp :: c# datatable column alias 
Csharp :: visibility bound to radio button wpf 
Csharp :: c# nunit initialize variables 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =