自定义异常中间件未捕获异常

custom exception middle-ware not catching exception

我有一个像这样的自定义中间件设置。

        using AutoWrapper.Wrappers;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Threading.Tasks;

    namespace BBBankApi
    {
        public class ExceptionMiddleware
        {
            private readonly RequestDelegate _next;
            private readonly ILogger<ExceptionMiddleware> _logger;

            public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
            {
                _next = next;
                _logger = logger;
            }
            public async Task Invoke(HttpContext context)
            {
                try
                {
                    await _next.Invoke(context);
                }
                catch (Exception ex)
                {
                    if (context.Response.HasStarted)
                    {
                        throw;
                    }

                    _logger.LogError(new EventId(), ex, ex.Message);
                    context.Response.ContentType = "application/json";
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    var json = JsonConvert.SerializeObject(new ApiException(ex));
                    await context.Response.WriteAsync(json);
                }
            }
        }
        public static class CustomExceptionMiddlewareExtensions
        {
            public static IApplicationBuilder UseCustomExceptiontusMiddleware(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware<ExceptionMiddleware>();
            }

        }
    }

在启动时是这样配置的

   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();                
        }

        app.UseCustomExceptiontusMiddleware(); //<-- *******Right Here
        app.UseApiResponseAndExceptionWrapper();


        app.UseCors(MyAllowSpecificOrigins);
        app.UseMvc(b =>
        {
            b.MapODataServiceRoute("odata", "odata", GetEdmModel());
        });
        app.UseHttpsRedirection();



        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();

        });
    }

当我发出请求时,我确实点击了 await _next.Invoke(context);行,但我在代码中提出了一个新的异常("Something Went Wrong")。但是在中间件的 catch 块中没有收到此异常。

我正在使用 https://vmsdurano.com/autowrapper-prettify-your-asp-net-core-apis-with-meaningful-responses/ 的 AutoWrapper 但我不这么认为,这在这里有很大的不同。

我认为不应该是问题的是问题。我不得不在 autowrapper 之后使用中间件。

            app.UseApiResponseAndExceptionWrapper();
        app.UseCustomExceptiontusMiddleware();

这种安排奏效了。