📜  ExceptionFilterAttribute 异常处理程序中间件未捕获 - C# 代码示例

📅  最后修改于: 2022-03-11 14:48:49.084000             🧑  作者: Mango

代码示例1
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));
});