Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

ExceptionFilterAttribute exception-handler-middleware-not-catching

You can try also Exception filters.
(of course, filters are not so flexible like as error handling middleware, which is better in general case, but - at least for me - filters are working fine without any issues)
That's what I'm using:

public class ExceptionGlobalFilter : ExceptionFilterAttribute
{
    private readonly ILogger logger;

    public ExceptionGlobalFilter(ILoggerFactory lf)
    {
        logger = lf.CreateLogger("ExceptionGlobalFilter");
    }


    public override void OnException(ExceptionContext context)
    {
        var customObject = new CustomObject(context.Exception);

        //TODO: Add logs
        if (context.Exception is BadRequestException)
        {
            context.Result = new BadRequestObjectResult(customObject);
        }
        else if (context.Exception is NotFoundException)
        {
            context.Result = new NotFoundObjectResult(customObject);
        }
        else
        {
            context.Result = new OkObjectResult(customObject);
        }

        base.OnException(context);
    }


    public override async Task OnExceptionAsync(ExceptionContext context)
    {
        await base.OnExceptionAsync(context);
        return;
    }
}

Startup.cs:

services.AddMvc(config =>
{
    config.Filters.Add(typeof(ExceptionGlobalFilter));
});
Comment

PREVIOUS NEXT
Code Example
Csharp :: cqrs design pattern .net core 
Csharp :: get current culture in controller asp.net core 6 
Csharp :: how to make a methode accessible from all the forms c# 
Csharp :: All and Any linq c# examlpe replace 
Csharp :: asp.net mvc table array binding arbitrary indices 
Csharp :: kendo razor textbox 
Csharp :: C#$ 
Csharp :: subarray c# 
Csharp :: Get mac address of Device - NAYCode.com 
Csharp :: unity variable in editor limit value 
Csharp :: assign a list to another in c# without a loop 
Csharp :: netmath hack 
Csharp :: c# check if object can be cast to type 
Csharp :: C# is folder 
Csharp :: ow-to-return-http-500-from-asp-net-core-rc2-web-api 
Csharp :: how to define a static color resource in xaml wpf 
Csharp :: one to many relationship in asp net entity framework with role 
Csharp :: C# today, yesterday, last week, last month 
Csharp :: unity how to get data of play session time in a text file? 
Csharp :: c# hashset 
Csharp :: how to not overwrite a text file in c# 
Csharp :: app rating within game in unity 
Csharp :: csharp nullable types 
Csharp :: is c# hard to learn 
Csharp :: Load Level Action for unity 
Csharp :: how to do Employing defensive code in the UI to ensure that the current frame is the most top level window in c# 
Html :: open page with html 
Html :: add mailto in html 
Html :: bootstrap Bootstrap link 
Html :: html character tab 
ADD CONTENT
Topic
Content
Source link
Name
4+8 =