'Database Errors codes returning from api layer to a ui layer sep project

I keep coming back to this but what should I be returning from my database service call in my WeightLifting Service I have this code.

public async void CopySessionsPlayersToWeightLiftingBySessionId(int sessionID)
{
        List<SessionPlayer> sessionsPlayers = new 
                                                 List<SessionPlayer>();
        sessionsPlayers = db.SessionPlayer.Where(w => w.SessionId ==
        sessionID).ToList();
        if (sessionsPlayers != null)
        {
            List<WeightLifting> weightLiftings = new List<WeightLifting>();
            foreach (var sessionPlayer in sessionsPlayers)
            {
                var player = db.Players.Where(w => w.Id == 
                    sessionPlayer.PlayerId).FirstOrDefault();
                WeightLifting weightLifting = new WeightLifting();
                weightLifting.SessionStartDate = sessionPlayer.StartDate;
                weightLifting.SessionEndDate = sessionPlayer.EndDate;
                weightLifting.TeamId=sessionPlayer.TeamId;
                weightLifting.SessionId = sessionPlayer.SessionId;
                weightLifting.PlayersId = sessionPlayer.PlayerId;
                weightLifting.PU = player.DefaultPU;
                weightLifting.PUReps = Convert.ToInt32(player.DefaultPUReps);
                weightLifting.BP = player.DefaultBP;
                weightLifting.TB = player.DefaultTB;
                weightLifting.TBReps = Convert.ToInt32(player.DefaultTBReps);
                weightLifting.OP = player.DefaultOP;
                weightLifting.OPReps = Convert.ToInt32(player.DefaultOPReps);
                weightLifting.APU = player.DefaultAdvancedPu;
                weightLifting.APUReps = Convert.ToInt32(player.DefaultAdvancedPuReps);
                weightLifting.IsActive = true;
                weightLifting.IsDeleted = false;
                weightLiftings.Add(weightLifting);
            }
            db.AddRange(weightLiftings);
            db.SaveChanges();
        }
    }

As I am just doing a save out my http client call is basically this.

public async Task<HttpStatusCode> 
   CopySessionsPlayersToWeightLiftingBySessionId(int Id)
{           
     EnsureHttpClientCreated();
     var json = JsonConvert.SerializeObject(Id);
     var httpContent = new StringContent(json, Encoding.UTF8, 
         "application/json");

     var httpResponse = await httpClient.PostAsync(Constants.BaseUrl 
         + Constants.ApiSegmant + 
         Constants.CopySessionsPlayersToWeightLiftingBySessionId + 
         $"?Id={Id}", httpContent);
        return httpResponse.StatusCode;
}

My Create Http Client code

private void EnsureHttpClientCreated()
{
  if (httpClient == null)
  {
       CreateHttpClient();
  }
}
private void CreateHttpClient()
{
        _httpClientHandler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
        };

        httpClient = new HttpClient(_httpClientHandler, false)
        {
            Timeout = _timeout
        };

        httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(ClientUserAgent);

        if (!string.IsNullOrWhiteSpace(Constants.BaseUrl))
        {
            httpClient.BaseAddress = new Uri(Constants.BaseUrl);
        }

        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));
    }

At the min only the ui will get a ok but how should I handle sending back an error here yes I could try catch around the save changes then put a BadContent but that feels messy?.



Solution 1:[1]

Consider using exception filters. They basically serve as a middleware that runs after your endpoint throws an exception to catch it and turn it into a specific response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quacke