tnblog
首页
登录

.net core 自定义Error规则

36人阅读 2019/10/28 14:23 总访问:10946 评论:0 手机 收藏
分类: .net后台框架


创建并添加自定义的错误处理事件

namespace AiDaSiBlog.API.Extensions
{
    public static class ExceptionHandlingExtensions
    {
        public static void UseMyExceptionHandler(this IApplicationBuilder app,ILoggerFactory loggerFactory)
        {

#warning 重写异常业务
            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("AiDaSiBlog.API.Extensions.ExceptionHandlingExtensions");
                        logger.LogError(500,ex.Error,ex.Error.Message);
                    }
                    await context.Response.WriteAsync(ex?.Error?.Message ?? "An Error Occurred.");
                });
            });
        }
    }
}

Startup.cs 类的 Configure 

app.UseMyExceptionHandler(loggerFactory);


评价
有钱人的开发有着你们不懂的快乐!O(* ̄︶ ̄*)O
排名
6
文章
6
粉丝
16
评论
8
{{item.ArticleTitle}}
{{item.BlogName}} : {{item.Content}}