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)
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? Or asp.net core will automatically handles the global exception/ Sql excption?
Please let me know correct method becuase i dont want to include try catch in each method
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. :)