一、局部异常处理:
在Action里面catch
二、全局异常处理:
1、默认的异常处理配置:
默认配置在StartUp文件的Configure中注册错误处理,显示开发者错误页面:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
}
2、 使用 UseExceptionHandler 处理
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//app.UseDeveloperExceptionPage();//返回错误页面,如果做api就不适合了
app.UseExceptionHandler(builder=> {
builder.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
//记录日志
}
await context.Response.WriteAsync(ex?.Error?.Message ?? "an error occure");
});
});
app.UseHttpsRedirection();
app.UseMvc();
}
封装成扩展方法,使用app.use...调用:
public static class ExceptionHandlingExtensions
{
public static void UseMyExceptionHandler(this IApplicationBuilder app,ILoggerFactory loggerFactory)
{
app.UseExceptionHandler(builder => {
builder.Run(async context =>
{
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
var ex = context.Features.Get<IExceptionHandlerFeature>();
if (ex != null)
{
//记录日志
var logger = loggerFactory.CreateLogger("BlogDemo.Api.Extensions.ExceptionHandlingExtensions");
logger.LogDebug(500, ex.Error, ex.Error.Message);
}
await context.Response.WriteAsync(ex?.Error?.Message ?? "an error occure");
});
});
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
//app.UseDeveloperExceptionPage();//返回错误页面,如果做api就不适合了
app.UseMyExceptionHandler(loggerFactory);
app.UseHttpsRedirection();
app.UseMvc();
}
|