Fork me on GitHub

ASP.NET Core ---异常处理

一、局部异常处理:

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

 

posted @ 2018-09-04 15:00  精进的小陈  阅读(1660)  评论(0编辑  收藏  举报