在ASP.NET Core 2.2或3中尝试捕获的全局异常

时间:2019-06-26 02:05:50

标签: c# asp.net exception asp.net-core

如果发生任何错误,我需要为我的所有控制器方法提供一个全局异常处理程序(我需要向客户端发送一些错误代码)。目前正在每个控制器中编写try catch块。以下是我的控制器方法。这是一种好方法还是请向我建议使用asp.net core 3预览版的解决方案/方法。

[HttpPost]
        public ActionResult<Caste> InsertCaste(CasteModel caste)
        {
            try
            {

                var result = casteService.InsertCaste(caste);

                return CreatedAtAction(nameof(InsertCaste), new { id = result.Id }, result);
            }
            catch (Exception ex)
            {
                Log.Logger.log().Error(ex.Message);
                return null;
            }
        }

1 个答案:

答案 0 :(得分:2)

ASP.NET Core中的一种方法是使用Middlewares。在Startup类和Configure方法中,添加以下代码:

   app.UseExceptionHandler(errorApp =>
   {
        errorApp.Run(async context =>
        {
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    context.Response.ContentType = "application/json";

                    var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if(contextFeature != null)
                    {  
                        await context.Response.WriteAsync(new ExceptionInfo()
                        {
                            StatusCode = context.Response.StatusCode,
                            Message = "Internal Server Error."
                        }.ToString());
                    }
        });
    });

ExceptionInfo类:

public class ExceptionInfo
{
    public int StatusCode { get; set; }
    public string Message { get; set; }

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

更新1:

中间件的顺序非常重要,您必须将其放在诸如mvc之类的任何其他中间件之前:

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseExceptionHandler(... like code above);

    app.UseHttpsRedirection();
    app.UseMvc();

更新2:

在记录异常的情况下,可以通过将记录器的类型添加到Configure类中的Startup方法中来注入记录器:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger logger)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseExceptionHandler(... like code above);

    app.UseHttpsRedirection();
    app.UseMvc();
}

更新3:

使用自定义中间件作为全局异常处理程序:

public class CustomErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILoggerManager _logger;

    public ExceptionMiddleware(RequestDelegate next, Ilogger logger)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            _logger.LogError($"Something went wrong: {ex}");
            await HandleExceptionAsync(httpContext, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        return context.Response.WriteAsync(new ExceptionInfo()
        {
            StatusCode = context.Response.StatusCode,
            Message = "Internal Server Error"
        }.ToString());
    }
}

然后以Configure方法使用它:

app.UseMiddleware<CustomErrorHandlerMiddleware>();

TL; DR:

Handle errors in ASP.NET Core

ASP.NET Core Middleware