.net 异常中间件未捕获异常

flseospp  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(156)

我创建了一个异常处理中间件类:

namespace FileSharingApp.API.Middleware
{
    public class GlobalErrorHandlingMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalErrorHandlingMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }

        }

        private static Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            HttpStatusCode status;

            var exceptionType = exception.GetType();

            if (exceptionType == typeof(InvalidOperationException))
            {
                status = HttpStatusCode.NotFound;
            }
            else if (exceptionType == typeof(PasswordIncorrectException))
            {
                status = HttpStatusCode.Unauthorized;
            }
            else
            {
                status = HttpStatusCode.InternalServerError;
            }

            var exceptionResult = JsonSerializer.Serialize(new { error = exception.Message, exception.StackTrace });
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)status;

            return context.Response.WriteAsync(exceptionResult);
        }

然后我创建了一个扩展方法来添加中间件:

public static class ApplicationBuilderExtensions
    {
        public static IApplicationBuilder AddGlobalErrorHandler(this IApplicationBuilder applicationBuilder)
            => applicationBuilder.UseMiddleware<GlobalErrorHandlingMiddleware>();
    }

然后在我的program.cs类中调用它:

var app = builder.Build();

app.AddGlobalErrorHandler();
app.UseExceptionHandler("/error");

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

我已经通过从一个端点抛出一个异常对此进行了测试:

[HttpPost("Login")]
public async Task<ActionResult<UserDto>> LoginUser([FromBody] LoginDto loginDto)
{
     throw new InvalidOperationException("Password is incorrect");
}

但是我的中间件类中的HandleExceptionAsync方法没有被命中(我添加了一个断点),并且向客户机返回了一个标准的500响应。
有人能看出我哪里做错了吗?

mum43rcc

mum43rcc1#

我的工作正常。
也许是因为你把应用程序放在了什么地方。
请检查我的github repo上的https://github.com/lucasdsalves/stack-overflow-74655126

相关问题