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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM