简体   繁体   English

ASP.NET MVC Core和Dapper中的全局异常/错误处理

[英]Global exception/error handling in asp.net mvc core and dapper

I am using Asp.net core and Dapper in our App.Here is my User Repository Add method.(connection string will be injected through dependency) 我在我们的应用程序中使用Asp.net core和Dapper。这是我的用户存储库Add方法(连接字符串将通过依赖项注入)

public User Add(User user)
        {
            string query = @"Insert into Users(UserName,Email,LastName,Password) values (@UserName , @Email, @LastName , @Password );
            select Cast(Scope_Identity() as int)";

            Try
            {
             using (var db = connectionFactory.GetOpenConnection())
             {
                  int id = db.Query<int>(query, user).Single();
                  user.UserId = id;
                  return user;
             }

        } Catch(Exception e){  //log exception}

        }

And in my startup class i have included global exception handler 在启动类中,我包含了全局异常处理程序

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
             loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // StatusCode pages to gracefully handle status codes 400-599.
                app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");

                app.UseExceptionHandler("/Home/Error");
            }

        }

My Quetion is whether try catch is requered in each method of repository? 我的问题是在每种存储库方法中是否都要求try catch? Or asp.net core will automatically handles the global exception/ Sql excption? 还是asp.net核心会自动处理全局异常/ sql例外?

Please let me know correct method becuase i dont want to include try catch in each method 请让我知道正确的方法,因为我不想在每种方法中都包含try catch

A try catch is the best way to be safe but in a perfect world best practice would be to write unit tests around those situations. 尝试捕获是确保安全的最佳方法,但是在理想情况下,最佳实践是围绕这些情况编写单元测试。 I came across this with my last stand alone project at work. 我在上一个独立的项目中遇到了这个问题。 A well written unit test will tell you the exact issue with your code. 编写良好的单元测试将告诉您代码的确切问题。 I love them. 我爱他们。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM