Should I use try catch exception handlers in controllers?

So I have a normal controller in core and I use entityframework core.

I have a repository injected in the controller that fetches data:

public async Task<IActionResult> Statistics() { var statsModel = await _repo.GetStatisticsModel(); return View(statsModel); } 


public async Task<StatisticsModel> GetStatisticsModel() { try { var stats = await _context.Statistics.AsNoTracking().ToListAsync(); var statsModel = new StatisticsModel(); if(stats.Any() == false) { statsModel.Title = "No statistics created"; return statsModel; } else { statsModel.Title = "Points"; statsModel.Points = stats; return statsModel; } } catch (Exception ex) { throw new ApplicationException($"Could not fetch data:'{ex.Message}'."); } } 

The idea is that if there are no statistics, the model would just return a title that says nothing is created and an empty list. So that when rendered in the view, it would just display nothing.

Do I even have to wrap any database call in a try-catch block? I think i have to because the database could be unavailable or broken(!?) etc out of my control.

This has never happened to me though. So what would happen? would the stats variable just be empty if the db was down so the emptycheck is enough to handle any errors? What if the call took too long?

Should I just drop the try-catch in the repo and use it in the controller call instead, or not ever there? It feels very natural using it on saving/updating data, but not on fetching.

Really appreciate any input on this. Thankyou

submitted by /u/bluMarmalade
[link] [comments]

Leave a Reply