c# - asp.net core 2.2 或 3 中 try catch 的全局异常

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

如果发生任何错误,我的所有 Controller 方法都需要一个全局异常处理程序(我需要向客户端发送一些错误代码)。目前正在每个 Controller 中编写 try catch block 。下面是我的 Controller 方法。这是好方法还是请建议我使用 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;
            }
        }

最佳答案

长话短说:

Handle errors in ASP.NET Core

ASP.NET Core Middleware

ASP.NET Core 中的一种方法是使用中间件。在 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:

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

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>();

关于c# - asp.net core 2.2 或 3 中 try catch 的全局异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56764185/

相关文章:

c# - propertychanged回调是否会在属性更改时立即发生?

c# - 自定义角色提供者不实现继承的抽象成员

c# - 从 ASP.NET MVC 创建打开的 XML Excel 工作表时出错

asp.net - 获取数据绑定(bind) Ext.NET GridPanel 上的当前数据项(行)

java - 运行方法两次

java - 当我尝试更新图表时,线程 "Thread-1"java.lang.NullPointerException 中发生异常

c# - 网络矩阵搜索

c# - Windows 7手机开发

scala - Exception和Throwable类之间有什么区别?

C# 格式化 JSON,值中带有反斜杠 '\'