如果发生任何错误,我的所有 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;
}
}
最佳答案
长话短说:
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/